Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should UIViewController add/remove observers on NSNotificationCenter?

If I add an observer to the [NSNotificationCenter defaultCenter] in my viewDidLoad should I be removing it in viewDidUnload?

like image 638
fuzzygoat Avatar asked Sep 30 '11 16:09

fuzzygoat


People also ask

Do you need to remove observers Swift?

If your app targets iOS 9.0 and later or macOS 10.11 and later, and you used addObserver(_:selector:name:object:) , you do not need to unregister the observer. If you forget or are unable to remove the observer, the system cleans up the next time it would have posted to it.

How do I remove a specific observer in Swift?

Removing registered observer For Selector approach, use NotificationCenter. default. removeObserver(self, name: notificationName , object: nil) , to remove the observer. For Block based approach, save the token you obtained by registering for notification in a property.

How do I delete an observer in Objective C?

When removing an observer, remove it with the most specific detail possible. For example, if you used a name and object to register the observer, use removeObserver:name:object: with the name and object.

How do I use notification observer in Swift?

First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()


2 Answers

If you need to add these in your initializer, you should remove it in the dealloc method. Ideally, you should only care about these notifications when you are currently onscreen or not.

The viewDid[Appear|Disappear] methods can be called multiple times during the lifetime of a UIViewController. Register for the notification in the viewDidAppear method and unregister it in viewDidDisappear.

like image 156
Jason Avatar answered Nov 09 '22 23:11

Jason


You should remove it in dealloc method.

like image 30
knuku Avatar answered Nov 10 '22 00:11

knuku