Where should I remove the observer for NSNotification
in Swift, since viewDidUnload
and dealloc()
are unavailable?
Use the method deinit . In Objective-C classes I would always remove NSNotificationCenter observers in the -dealloc method, but a Swift class doesn't have a -dealloc method. Instead, Swift has a deinit method.
specifies. 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.
I'd recommend, that you add a call [notificationCenter removeObserver: self] in method dealloc of those classes, which you intend to use as observers, as it is the last chance to unregister an observer cleanly. This will, however, only protect you against crashes due to the notification center notifying dead objects.
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()
As of iOS 9 (and OS X 10.11), you don't need to remove observers yourself, if you're not using block based observers though. The system will do it for you, since it uses zeroing-weak references for observers, where it can.
And if you are using block based observers, make sure you capture self weakly using [weak self]
in the closure's capture list, and remove observer in deinit
method. If you don't use weak reference to self, deinit
method (and thus removal of that observer) will never be called since Notification Center will hold a strong reference to it indefinitely.
More info can be found at Foundation Release Notes for OS X v10.11 and iOS 9.
If the observer is able to be stored as a zeroing-weak reference the underlying storage will store the observer as a zeroing weak reference, alternatively if the object cannot be stored weakly (i.e. it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) it will store the object as a non-weak zeroing reference. This means that observers are not required to un-register in their deallocation method.
Block based observers via the -[NSNotificationCenter addObserverForName: object: queue: usingBlock] method still need to be un-registered when no longer in use since the system still holds a strong reference to these observers.
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