Post of NSNotificationCenter causing “EXC_BAD_ACCESS” exception

↘锁芯ラ 提交于 2019-12-18 10:58:15

问题


A UIViewController adds itself to the default center:

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(editFood)
 name:@"editFood"
 object:nil];

Then a UITableView delegate NSObject posts a NSNotification:

[[NSNotificationCenter defaultCenter]
 postNotificationName:@"editFood"
 object:self];

During run time it get a EXC_BAD_ACCESS exception.

Is the defaultCenter getting released somewhere? The same concept works when I post a notification to a UIViewController from a UIViewController, but that shouldn't matter, right?


回答1:


One of your subscribers has been deallocated. Make sure to call [[NSNotificationCenter defaultCenter] removeObserver:self] in your dealloc (if not sooner).




回答2:


EXC_BAD_ACCESS can happen even after verifying dealloc exists like so:

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self]
}

The above will solve the problem most of the time, but apparently my cause was that I was indirectly adding the observer with a selector: set to nil as follows:

[NSNotificationCenter.defaultCenter addObserver:self
                                         selector:nil
                                             name:notificationName
                                           object:nil];

...so when I posted something with that notificationName, EXC_BAD_ACCESS occurred.

The solution was to send a selector that actually points to something.



来源:https://stackoverflow.com/questions/5668752/post-of-nsnotificationcenter-causing-exc-bad-access-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!