NSNotificationCenter的帖子导致"EXC_BAD_ACCESS"异常

Pau*_*dan 62 iphone exc-bad-access objective-c nsnotificationcenter ios

A UIViewController将自己添加到默认中心:

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(editFood)
 name:@"editFood"
 object:nil];
Run Code Online (Sandbox Code Playgroud)

然后UITableView代表NSObject发布一个NSNotification:

[[NSNotificationCenter defaultCenter]
 postNotificationName:@"editFood"
 object:self];
Run Code Online (Sandbox Code Playgroud)

在运行时,它会获得EXC_BAD_ACCESS异常.

是在defaultCenter哪里获得释放?当我从UIViewController向UIViewController发布通知时,同样的概念也有效,但这不重要,对吧?

Ben*_*man 128

您的一个订户已被取消分配.一定要打电话给[[NSNotificationCenter defaultCenter] removeObserver:self]你的dealloc(如果不是更早).

  • @Paul:Zombies乐器在调试这类问题时非常有帮助. (4认同)
  • 谢谢,我刚刚意识到我的错误(看了这个并研究了四个小时).呼叫释放后我试图引用的对象.调试器使它看起来就像是抛出EXC_BAD_ACCESS异常的地方. (3认同)
  • EXC_BAD_ACCESS也不例外,它是无效的内存访问 (3认同)

kra*_*vil 10

EXC_BAD_ACCESS 即使在验证dealloc之后也会发生这种情况:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self]
}
Run Code Online (Sandbox Code Playgroud)

上面将解决大多数时间的问题,但显然我的原因是我间接地向观察者添加了如下selector:集合nil:

[NSNotificationCenter.defaultCenter addObserver:self
                                         selector:nil
                                             name:notificationName
                                           object:nil];
Run Code Online (Sandbox Code Playgroud)

...所以当我发布的内容时notificationName,EXC_BAD_ACCESS发生了.

解决方案是发送一个实际指向某事物的选择器.