我正在尝试创建NSInvocationOperation,以便它应该使用params调用对象的方法
- (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(loadImagesWithOperation:)和@selector(loadImagesWithOperation:bounds:),等@selector的代码块中使用不同的语法,但没有成功。
用params定义选择器和函数的正确方法是什么?
谢谢。
发布于 2011-01-24 22:53:27
定义接受参数的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 of 1的对象,因为您使用的是+alloc,所以当它们被添加到NSArray时,它们会被发送-retain消息,从而将retainCount增加到2。
当这个NSArray被解除分配时,这些对象将不会被释放,因为它们的retainCount将是1,而不是0。
这个问题有三种解决办法:
在将这些对象添加到NSArray.
NSNumber的numberWithInt:类方法之前,autorelease消息,以获得对这些NSNumber对象的自动释放的NSNumber NSArray中,然后在添加后发送-release消息。<>H 233G 234发布于 2011-01-26 15:55:39
一切都变好了。我曾尝试在@selector的代码块中使用不同的语法,比如@selector(loadImagesWithOperation:)和@selector(loadImagesWithOperationsb界:),但没有成功。
initWithTarget:selector:object:采用一个可以接受0或1个参数的选择器,不能接受更多的参数(而不是两个)。一个参数必须是一个对象。如果您需要更多的参数,可以使用块或重构您的代码(将数组与其馀的对象一起传递是一种潜在的解决方案,是的--有点像您在该代码中所做的事情(尽管注意内存泄漏)。
崩溃与您显示的代码无关。事故发生后。
还请注意,在Cocoa/iOS中,以get为首的方法有一个非常特殊的含义,而不是用于这种模式。我建议loadImages。
https://stackoverflow.com/questions/4788101
复制相似问题