BAD ACCESS 异常 performSelector:WithObject: 方法

Man*_*nOx 1 iphone exc-bad-access objective-c ios

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

SEL newSelector = NSSelectorFromString(@"mySelector:withCustomObject:");
[self performSelector:newSelector withObject:myCustomObject];
Run Code Online (Sandbox Code Playgroud)

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

[self performSelector:@selector(mySelector:withCustomObject:) withObject:myCustomObject];
Run Code Online (Sandbox Code Playgroud)

有用。

关于为什么会发生这种情况的任何想法?PS:没有一个参数是nil。

更多代码:

// 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"];
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*n R 5

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

- (void)mySelector:(id)firstArgument withCustomArgument:(id)secondArgument { ... }
Run Code Online (Sandbox Code Playgroud)

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

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