3

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.

SundayMonday
  • 19,147
  • 29
  • 100
  • 154

2 Answers2

8

For iOS 9+ and OS X 10.11+, the WWDC 2015 session 202 "What's New in Cocoa" announced:

NSNotificationCenter
Deallocated observers are automatically unregistered

let center = NSNotificationCenter.defaultCenter()
center.addObserver(self,
                   selector: "localeChanged:",
                   name: NSCurrentLocaleDidChangeNotification,
                   object: nil)

No need to call

let center = NSNotificationCenter.defaultCenter()
center.removeObserver(self,
                      name: NSCurrentLocaleDidChangeNotification,
                      object: nil)

see: video at 33:27, pdf slide 241

marc-medley
  • 8,931
  • 5
  • 60
  • 66
8

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.

Michael Dautermann
  • 88,797
  • 17
  • 166
  • 215
  • Interesting. So in iOS 5+ what gets called in place of viewDidUnload in low memory conditions? – SundayMonday Jan 01 '12 at 19:07
  • 1
    `didReceiveMemoryWarning` continues to get called in case of low memory conditions. Also, check out Apple's [UIViewController](http://developer.apple.com/library/ios/#documentation/UIKit/Reference/UIViewController_Class/Reference/Reference.html) (specifically the "Memory Management" section there): When a low-memory warning occurs, the UIViewController class purges its views if it knows it can reload or recreate them again later. If this happens, it also calls the viewDidUnload method to give your code a chance to relinquish ownership of any objects associated with your view hierarchy. – Michael Dautermann Jan 01 '12 at 19:12