Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift NotificationCenter remove observer quickest way

I am adding a number of observers in my viewController -- applicationWillResignActive, applicationDidEnterBackground, and many others. I want to remove self as observer to all registered notifications in one line. My question is whether the following line is enough to do that, or are there issues with this code?

deinit {
   NotificationCenter.default.removeObserver(self)
}
like image 761
Deepak Sharma Avatar asked Aug 08 '18 11:08

Deepak Sharma


1 Answers

So I'm working with this in an app right now and the answer might not be as straightforward.

In the documentation, it does state that for iOS 9 and above you are no longer required to explicitly remove the observer in the deinit/dealloc methods for objects. https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver

However, it appears that this is only true for selector based notification observers. I'll be referencing this blog post: https://oleb.net/blog/2018/01/notificationcenter-removeobserver/.

If you are using block based observers you must still manually remove the observers.

addObserver(forName:object:queue:using:) 

The best general way to do this is to capture the tokens in an array, append them when you add the observer and use them for removal when you deinit/dealloc or otherwise need to remove observer behavior for your object.

in your VC/object properties create an array to store observer 'tokens'

var notifObservers = [NSObjectProtocol]()

Register for a block based notification by capturing the function return object and storing it as a token

let observer = NotificationCenter.default.addObserver(forName: , object: , queue:) { [weak self] notification in
    // do a thing here
}
notifObservers.append(observer)

Removal

for observer in notifObservers {
    NotificationCenter.default.removeObserver(observer)
}
notifObservers.removeAll()
like image 71
Daniel Yount Avatar answered Oct 12 '22 10:10

Daniel Yount