What's the better way to addObserver/removeObserver with NSNotificationCenter?
this depends on your scenario, usually the best approach is to add in viewDidLoad
and remove in dealloc
and in viewDidUnload
(deprecated in iOS 9.0, use dealloc
only), but there are some cases when you have same method in different classes like UI effects and want to call only current screen's method using notification, then you will have to add the observer in viewWillAppear
and remove it in viewWillDisappear
or viewDidAppear
/viewDidDisappear
Edit: A note from comments, thanks @honey.
Though now since iOS 9, you no longer need to care about removing the observer. See Apple release notes: "In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated..
I would normally put it in -viewDidAppear:
and -viewDidDisapear:
(or -viewWillAppear:
and -viewWillDisappear:
) simply because in every case I came across I'm only interested in the notification if the view is actually displayed.
It's probably a premature optimisation (your code for handling the notification could take some time, but might be useless if the view is not displayed), but then it's also no more code - it's the same code just in a different method...