首页 > 解决方案 > 手动删除 iOS 9.0 及更高版本的通知观察器

问题描述

我想知道是否可以删除 iOS9.0 及更高版本的通知观察者。苹果文档说,一旦视图消失,通知将自动删除,这是真的,但并不完全正确。即使视图消失了,我的 tarBarController 也会调用 UIApplication.willResignActiveNotification 。

如果 tarBarController 提供了presentViewController,则presentViewController 调用通知并且tarBarController 执行相同的操作,即使我删除了tarBarController 中的观察者

//TabBarController

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
 if #available(iOS 13.0, *) {
                        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillDisappear(notification:)), name: UIScene.willDeactivateNotification, object: nil)
                          } else {
                              NotificationCenter.default.addObserver(self, selector: #selector(applicationWillDisappear(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
                          }
}



override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

    NotificationCenter.default.removeObserver(self) // there is no need to remove this observer in iOS 9 and later , but TarBarController doesn't dealloc 

}




//PresentedViewController

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(true)
 if #available(iOS 13.0, *) {
                        NotificationCenter.default.addObserver(self, selector: #selector(applicationWillDisappear(notification:)), name: UIScene.willDeactivateNotification, object: nil)
                          } else {
                              NotificationCenter.default.addObserver(self, selector: #selector(applicationWillDisappear(notification:)), name: UIApplication.willResignActiveNotification, object: nil)
                          }
}



override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(true)

    // the presentedViewController removes this observer which is fine

}

标签: swift

解决方案


推荐阅读