NSNotification, addObserver and removeObserver - removeObserver both in ViewDidUnload and dealloc?
I want to add a view controller as observer of a notification.
When the selector method is called, I'll alert the user. I would that this alert ap开发者_JAVA技巧pears only when this view controller is the top view controller.
I thought to add it as observer in the viewDidLoad
method. But where is the better remove the view controller as observer?
Could it be a problem if I remove it both in viewDidUnload
and dealloc
?
No. According to the documentation:
Removes all the entries specifying a given observer from the receiver’s dispatch table.
If there are no such entries, there is nothing to remove, so it's not a problem.
However, depending on how you're using this, adding it as an observer in viewDidLoad doesn't mean that it will only be used when that view controller is "the top view controller" (for instance, if you have several tabs and move from one to the other, unless you get memory warnings the other (non-visible) tabs' views won't be unloaded when you move away from them).
Depending on your goal, it might be better to add the observer on viewDidAppear (and if so, remove on viewWillDisappear).
精彩评论