Objective-C: Where to remove observer for NSNotification?

前端 未结 14 1373
北海茫月
北海茫月 2020-11-29 19:37

I have an objective C class. In it, I created a init method and set up a NSNotification in it

//Set up NSNotification
[[NSNotificationCenter defaultCenter] a         


        
相关标签:
14条回答
  • 2020-11-29 20:01

    In general I put it into the dealloc method.

    0 讨论(0)
  • 2020-11-29 20:02

    SWIFT 3

    There are two cases of using notifications: - they are needed only when the view controller is on screen; - they are needed always, even if user opened another screen over current.

    For the first case the correct place to add and remove observer are:

    /// Add observers
    ///
    /// - Parameter animated: the animation flag
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        NotificationCenter.default.addObserver(...)
    }
    
    /// Remove observers
    ///
    /// - Parameter animated: the animation flag
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    

    for the second case the correct way is:

    /// Add observers
    override func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(...)
    }
    
    /// Remove observers
    ///
    /// - Parameter animated: the animation flag
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        if self.isBeingDismissed // remove only when view controller is removed disappear forever
        || !(self.navigationController?.viewControllers.contains(self) ?? true) {
            NotificationCenter.default.removeObserver(self)
        }
    }
    

    And never put removeObserver in deinit{ ... } - it's a MISTAKE!

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