Swift - Is the correct place to call .removeObserver always deinit()?

北战南征 提交于 2021-02-08 08:01:33

问题


New StackOverflow user here (first time posting, long time lurking w/o an account). Before I begin, these are some previously answered questions that I've found to be helpful but have not completely resolved my issue:

How to safely removeObserver (Swift)

The right place to call .removeObserver for NSNotificationCenter = Swift deinit()?

From these I have constructed a BaseView controller with which to control the behaviour of my app under various circumstances (e.g. an API call to check for updates when the app is brought back into the foreground)

class BaseViewController : UIViewController {

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}

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

@objc func applicationWillEnterForeground() {

}

@objc func applicationDidEnterBackground() {

}

deinit {
    print("WORKING - deinit BaseViewController")
    NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}

}

However, my issue is that I am required to use other NotificationCenter observers to dynamically control a navigation (progress) bar that depends on where in the app the user is (and what they do there, in isolation from the other areas).

My question is then: "Is the correct place to call .removeObserver always deinit()?" or, if not, are there any key places where one should consider adding .removeObserver calls?

If it helps, the navigation bar for each section of the app is attached to a MainPagerVC (a UIPageViewController) which is reused and switched in and out via a LGSideMenuController


回答1:


In your case you should remove observers in viewWillDisappear

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    NotificationCenter.default.removeObserver(self, name: UIApplication.willEnterForegroundNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: UIApplication.didEnterBackgroundNotification, object: nil)
}


来源:https://stackoverflow.com/questions/53394779/swift-is-the-correct-place-to-call-removeobserver-always-deinit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!