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

976 views Asked by At

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

There are 1 answers

2
Robert Dresler On BEST ANSWER

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)
}