简体   繁体   English

是否应该在 iOS 中使用 removeObserver(self) 删除通知?

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

Should notification be removed using self in iOS?是否应该在 iOS 中使用 self 删除通知?

Team mate have registered a notification in viewWillAppear and removed in viewDidDisappear like,队友在viewWillAppear注册了一个通知,并在viewDidDisappear删除,例如,

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.在查看时,我评论并建议删除带有显式名称的通知而不是用self删除,因为我认为将来可能需要在viewWillLoad中注册一些其他通知,这些通知不应受到调用NotificationCenter.default.removeObserver(self)意外或开发人员错误。 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.队友回复说用NotificationCenter.default.removeObserver(self)删除是完全可以的,因为我们暂时没有注册其他通知。 I was seeking for reference or guideline to convince him, why it is important to remove notification explicitly using name rather by self .我正在寻求参考或指导以说服他,为什么使用 name 而不是self明确删除通知很重要。

Is there any guideline from Apple about best practice of removing notification observers? Apple 是否有任何关于删除通知观察者的最佳实践的指南?

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

The thing is it's not future safe to remove all notification in viewWillDisappear .问题是在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.在 iOS 9 之后,没有必要调用 removeObserver,因为 iOS 不会尝试通知已释放的对象。 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在您的情况下,即使视图控制器不可见但存在于导航堆栈中,您也想收听您应该在deinit执行的deinit

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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