iosdeallocviewdidloadnsnotificationcenterviewdidunload

Best practice for adding/removing observers to/from NSNotificationCenter


What's the best practice for adding and removing observers to/from NSNotificationCenter?

I'm wondering if adding self as an observer in viewDidLoad and removing self in viewDidUnload is sufficient. Or perhaps I should remove self in dealloc as well.

Perhaps low memory conditions need to be considered. I could see adding in viewDidLoad and removing in dealloc being problematic: viewDidUnload is called due to low memory... then viewDidLoad is called when the view is displayed again... now self has been added as an observer twice w/o being removed (since dealloc wasn't called).

Note: I'm considering just a basic example where self refers to a UIViewController subclass.


Solution

  • I usually do my UIViewController observer registering in viewWillAppear and my removing in viewWillDisappear.

    viewWillDisappear seems like a safer choice to me than viewWillUnload since the latter method only gets called in low-memory situations on iOS versions older than 5.0.

    The most appropriate answer probably depends on what your view controller is doing. Do you expect to get (and need to react to) notifications before your view even gets displayed? If so, maybe adding the observer in viewDidLoad is the right thing for you.