Removing a NSNotificationCenter observer in iOS 5 ARC

Skoota picture Skoota · Dec 4, 2011 · Viewed 16.1k times · Source

I have an iOS 5 ARC-based project, and am having difficulty about where I should be removing the observer for the NSNotificationCenter observations which I have registered within a UIViewController. Similar posts on SO have said this should be done in the -dealloc method. Even though this method is not required in ARC projects I have added it with the following code:

- (void)dealloc {

    [[NSNotificationCenter defaultCenter] removeObserver:self];

}

As a test, I open the UIViewController (within a UINavigationController), do some things which trigger the notifications, and then pop it off the stack by tapping the Back button. I then reopen the UIViewController, and do some more things to trigger the notifications, but notice that each callback is being called twice - an indication that the previous notifications have not been deregistered. Repeating this procedure just causes each callback to be called more than more times, so they appear to never be deregistering.

Any help would be appreciated!

Answer

Michael Dautermann picture Michael Dautermann · Dec 4, 2011

It's pretty clear your dealloc method isn't being called (nor is the removeObserver call).

Why not remove your UIViewController's observer in the viewDidUnload: or viewWillDisappear: methods?