Swift NotificationCenter remove observer quickest way

天涯浪子 提交于 2020-04-11 15:23:43

问题


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)
}

回答1:


@Sh_Khan is right:

NotificationCenter.default.removeObserver(self)

You can get even further, as mentioned in the Apple Documentation:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.




回答2:


Yes

NotificationCenter.default.removeObserver(self)

this line is sufficient to remove the vc observation as long as all are added with

NotificationCenter.default.addObserver



回答3:


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()


来源:https://stackoverflow.com/questions/51745194/swift-notificationcenter-remove-observer-quickest-way

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!