BAD ACCESS异常performSelector:WithObject:方法

时间:2012-08-21 20:19:10

标签: iphone objective-c ios exc-bad-access

当我从一个实现我试图调用的方法的对象调用performSelector:withObject:时,我得到一个EXC_BAD_ACCESS异常。这是我的代码

SEL newSelector = NSSelectorFromString(@"mySelector:withCustomObject:");
[self performSelector:newSelector withObject:myCustomObject];

这会导致崩溃。但是当我这样做时

[self performSelector:@selector(mySelector:withCustomObject:) withObject:myCustomObject];

它有效。

有关为何发生这种情况的任何想法? PS:没有参数是零。

更多代码:

// My code to call this method
SEL newSelector = NSSelectorFromString(@"mySelector:withCustomObject:");
[self performSelector:newSelector withObject:self withObject:myCustomObject];

// this code is NOT called.
- (void) mySelector:(jObject *)sender withCustomObject:(jEvent *)customObject
{
    NSDictionary *handlerData = [aProperty objectAtIndex:[event positionInMethodStack]];
    NSString *newTitle = [handlerData objectForKey:@"newTitle"];
}

1 个答案:

答案 0 :(得分:4)

"mySelector:withCustomObject:"是带有2个参数的方法的签名,例如

- (void)mySelector:(id)firstArgument withCustomArgument:(id)secondArgument { ... }

但是你调用performSelector:withObject:,它只向mySelector发送一个只有一个参数的消息。第二个参数是未定义的,这可能导致崩溃。

因此,如果mySelector实际上有2个参数,请使用performSelector:withObject:withObject:,否则修复选择器的签名。