首页 > 解决方案 > 即使我在 viewWillAppear 中注册并在 viewWillDissapear 中取消注册,也会多次调用观察者方法

问题描述

即使我在 viewWillAppear 中注册并在 viewWillDissapear 中取消注册,观察者方法也会被多次调用。

override func viewWillAppear(_ animated: Bool) {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(handlePushNotification(notification:)),
                                           name: NSNotification.Name(rawValue: "abc"),
                                           object: nil)

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "abc"), object: nil)
}

标签: iosswiftswift4nsnotificationcenter

解决方案


对于具有属性观察者的成员变量,这是一个很好的用例:只需让通知观察者成为 View Controller 子类的成员,并在 willSet 块内处理通知观察者的清理:

class MyViewController: UIViewController {

    var notificationObserver: Any? {
        willSet {
            // if notificationObserver is not null, unregister it
            if let observer = notificationObserver {
                NotificationCenter.default.removeObserver(observer)
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        notificationObserver = NotificationCenter.default.addObserver(self,
                                       selector: #selector(handlePushNotification(notification:)),
                                       name: NSNotification.Name(rawValue: "abc"),
                                       object: nil)
    }

    override func viewWillDisappear(_ animated: Bool) {
        notificationObserver = nil
    }

}

这将确保现有观察者在创建新观察者时始终未注册。

如果您仍然收到多个回调,则意味着通知被多次发送。


推荐阅读