Swift NotificationCenter remove observer quickest way

后端 未结 3 1340
陌清茗
陌清茗 2021-02-09 23:31

I am adding a number of observers in my viewController -- applicationWillResignActive, applicationDidEnterBackground, and many others. I w

相关标签:
3条回答
  • 2021-02-09 23:48

    Yes

    NotificationCenter.default.removeObserver(self)
    

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

    NotificationCenter.default.addObserver
    
    0 讨论(0)
  • 2021-02-09 23:49

    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()
    
    0 讨论(0)
  • 2021-02-09 23:57

    @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.

    0 讨论(0)
提交回复
热议问题