手动删除iOS 9.0和更高版本的通知观察器

时间:2019-10-11 08:04:08

标签: swift

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

如果tarBarController呈现了presentedViewController,则即使我删除了tarBarController中的观察者,presentatedViewController也会调用通知,并且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

}

0 个答案:

没有答案