If I add an observer to the [NSNotificationCenter defaultCenter]
in my viewDidLoad
should I be removing it in viewDidUnload
?
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.
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.
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.
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()
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
.
You should remove it in dealloc
method.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With