gpt4 book ai didi

objective-c - NSInvocationOperation 使用参数定义选择器

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:05:13 26 4
gpt4 key购买 nike

我正在尝试创建 NSInvocationOperation 以便它应该使用参数调用对象的方法

- (void) getImages: (NSRange) bounds
{
NSOperationQueue *queue = [NSOperationQueue new];
NSArray * params = [NSArray arrayWithObjects:
[[NSNumber alloc] initWithInt: bounds.location],
[[NSNumber alloc] initWithInt: bounds.length]];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(loadImagesWithOperation)
object:params];

[queue addOperation:operation];
[operation release];

}

- (void) loadImagesWithOperation:(NSArray*)bounds {
NSLog(@"loadImagesWithOperation");
}

此代码因 EXC_BAD_ACCESS 而崩溃。如果我将要调用的函数的定义更改为此

- (void) loadImagesWithOperation {
NSLog(@"loadImagesWithOperation");
}

一切都会好起来的。我尝试在 @selector 的代码块中使用不同的语法,例如 @selector(loadImagesWithOperation:)@selector(loadImagesWithOperation:bounds:),但没有成功。

用参数定义选择器和函数的正确方法是什么?

谢谢。

最佳答案

定义 SEL 的正确方法采用参数的方法是为每个参数使用冒号 ( ":") 字符,因此在您的情况下,选择器将如下所示:

@selector(loadImagesWithOperation:)

所以,你的 NSInvocationOperation对象应该像这样初始化:

NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(loadImagesWithOperation:)
object:params];

哦,作为旁注,您在 NSArray 的初始化过程中存在内存泄漏在getImages: :

NSArray * params = [NSArray arrayWithObjects:
[[NSNumber alloc] initWithInt: bounds.location],
[[NSNumber alloc] initWithInt: bounds.length]];

这将添加已经具有 retainCount 的对象的 1因为你正在使用 +alloc , 所以当它们被添加到 NSArray , 他们会收到 -retain消息,从而增加 retainCount2 .

当这个NSArray被释放,这些对象将不会被释放,因为它们的 retainCount将是 1 , 不是 0 .

这个问题有三种解决方案:

  1. 发送autorelease在将这些对象添加到 NSArray 之前向每个对象发送消息.
  2. 使用NSNumbernumberWithInt:获取自动释放的类方法 NSNumber对象。
  3. 创建对这些 NSNumber 的引用对象,将它们添加到 NSArray ,然后在添加后,向他们发送 -release消息。

关于objective-c - NSInvocationOperation 使用参数定义选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4788101/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com