How to stop the Observer in NSNotification to called twice?

前端 未结 7 1151
被撕碎了的回忆
被撕碎了的回忆 2020-12-02 20:08

I have an observer of NSNotification which is called twice. I do not know what to do with it.

I googled it but no solution found.

[[NSNo         


        
相关标签:
7条回答
  • 2020-12-02 20:40

    For those looking for a solution in Swift 2.2 and above and who have reached this question like me you can create an extension as follows :

    import Foundation
    
    extension NSNotificationCenter {
      func setObserver(observer: AnyObject, selector: Selector, name: String?, object: AnyObject?) {
        NSNotificationCenter.defaultCenter().removeObserver(observer, name: name, object: object)
        NSNotificationCenter.defaultCenter().addObserver(observer, selector: selector, name: name, object: object)
      }
    }
    

    You can call this method as follows :

    NSNotificationCenter.defaultCenter().setObserver(self, selector: #selector(methodName), name: "name", object: nil)
    

    The extension will handle the removal of previous observer if it exists. Even if there was no previous observer present this code won't crash.

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