简体   繁体   中英

Adding observer to NSNotificationCenter second time causes EXC_BAD_ACCESS

Hypothetical scenario:

In my viewDidLoad method I am adding view controller as an observer for custom notification (say, notification MyFooNotification ). Later in the process when view is loaded the notification gets posted and controller processes it. When I leave the controller with it's view I DO NOT remove the observer (intentionally) in viewDidUnload . Next time when opening the view, the observer gets added again, but now when the observed notification gets posted - I get EXC_BAD_ACCESS .

Can anyone explain why this is happenning.

PS I do know that I should remove it in viewDidUnload I'm just curious about the lower level details.

Most likely because the original view controller has been deallocated because it was popped off a navigation stack (or similar), but NSNotificationCenter still has a reference to it. Thus when the notification is posted again, NSNotificationCenter attempts to notify the now deallocated view controller and gets EXC_BAD_ACCESS as a result.

If you ever have an object add itself to NSNotificationCenter as an observer you need to make sure you remove it during dealloc .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM