How to avoid adding multiple NSNotification observer?

前端 未结 3 1545
日久生厌
日久生厌 2020-11-30 04:19

Right now the API doesn\'t seem to provide a way to detect if an observer has already been added for a particular NSNotification. What\'s the best way to avoid adding multi

3条回答
  •  执念已碎
    2020-11-30 05:20

    The Upvoted answer with extension NotificationCenter { ... } did not work for me, since my app was creating a new instance of a viewController (this had a Notification observer) every time a notification was posted, so removing an observer on a new instance of a viewController obviously doesn't work. Previous instances of the viewController that had Notification Observers were getting called.

    The below worked for me, since this was removing the Notification Observer as soon as the view was being disappeared.

    // Notification observer added 
    
    override func viewWillAppear(_ animated: Bool) {
    
        NotificationCenter.default.addObserver(self, selector: #selector(self.someFunc(notification:)), name: Notification.Name("myNotification"), object: nil)
    
    
    }
    
    
    // Notification observer removed 
    
    override func viewWillDisappear(_ animated: Bool) {
    
        NotificationCenter.default.removeObserver(self, name: Notification.Name("myNotification"), object: nil)
    
    
    }
    

提交回复
热议问题