【问题标题】:BAD ACCESS exception performSelector:WithObject: methodBAD ACCESS 异常 performSelector:WithObject: 方法
【发布时间】:2012-08-21 20:19:10
【问题描述】:

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

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

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

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

它有效。

关于为什么会发生这种情况的任何想法? 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"];
}

【问题讨论】:

  • 崩溃时消息是否说明了什么具体内容?
  • 不,我一遍又一遍地点击(调试)继续按钮,它只是在同一个屏幕上显示相同的错误,而不会崩溃并在控制台中记录错误。
  • 这很可能是不相关的内存问题:两段代码看起来相同。

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


【解决方案1】:

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

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

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

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

【讨论】:

  • 好的,所以现在我没有收到 EXC_BAD_ACCESS 错误,现在我收到了 'NSInvalidArgumentException',原因:'*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'没有一个参数是零。而且我的方法没有被调用。
  • 代码中的数组在哪里? - 你能展示mySelector方法吗?
  • 该方法显然没有被调用。但这是标题 - (void) mySelector:(id)sender withCustomObject:(CustomObject *)object;
  • 你确定调用performSelector时会抛出NSInvalidArgumentException吗?
  • 是的,我在预制件选择器上设置了一个断点,当达到断点时,我点击继续,它会抛出一个带有 NSINvalidArgument 错误的 SIGBart 错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
相关资源
最近更新 更多