简体   繁体   中英

Should notifications be removed using removeObserver(self) in iOS?

Should notification be removed using self in iOS?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self, selector: #selector(onDidReceiveData(_:)), name: .didReceiveData, object: API.shared)
}

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self)
}

While reviewing I have commented and suggested to remove notification with explicit name instead of removing with self because, I think in future some other notifications might need to be registered in viewWillLoad which should not be affected by the call NotificationCenter.default.removeObserver(self) by accident or by developers mistake. My suggestion was to remove observer using,

override func viewDidDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
}

Team mates replied that removing with NotificationCenter.default.removeObserver(self) is perfectly ok because we do not register other notification for now. I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self .

Is there any guideline from Apple about best practice of removing notification observers?

在 iOS 9 之后,无需移除观察者,因为 iOS 会从解除分配的 ViewController 中移除观察者

The thing is it's not future safe to remove all notification in viewWillDisappear . It's not a good practice for an obvious reason but it's not documented. After iOS 9 it's not necessary to call removeObserver because iOS not try to notify deallocated objects. In your case, you want to listen even if view controller is not visible but present in the navigation stack you should do in deinit

    class ViewController: UIViewController {
    deinit {
     NotificationCenter.default.removeObserver(self, name:.didReceiveData, object: nil)
    }
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM