Best practice for adding/removing observers to/from NSNotificationCenter
-
11-04-2021 - |
题
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.
解决方案
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.
其他提示
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