简体   繁体   中英

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 appears 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM