10

I've read a lot of suggestions for the right place to call .removeObserver for NSNotificationCenter since viewDidUnload is not an option.

I was just wondering if the new deinit() in Swift would be a good choice?

-nick

nick
  • 1,147
  • 1
  • 11
  • 12
  • viewDidUnload was never an option. When do you add the observer? – jrturton Jul 31 '14 at 21:49
  • Not sure about that either. My gut says viewDidLoad, but some seem to think pairing viewWillAppear for adding and viewWillDisappear for removing. Others have stated that dealloc would be a good place for removing. I just thought removing in deinit() as the class is killed might be a good choice. – nick Jul 31 '14 at 21:56

2 Answers2

10

It really depends on the role of the class where you subscribe to NSNotificationCenter notifications. If you are subscribing in:

UIView

Then you should unsubscribe as soon as view gets invisible to the user. To save CPU cycles and not consume resources while user does not see the view.

UIViewController

Here it also depends on kind of action that you are going to perform in response to notification. If it is just a UI adjustment that you should unsubscribe as soon as view controller disappears from the screen.

You App Service layer

Here it is OK to have .removeObserver inside deinit(). however even here I tend to suggest you to be more explicit about when you subscribe and unsubscribe from NSNotificationCenternotifications and put them in start and stop methods of your service.

Keenle
  • 12,010
  • 3
  • 37
  • 46
  • Thanks Keenie. That does help. I'm just observing a text field in a view controller, so I guess the viewwillAppear and viewWillDisappear methods are the right choice anyway. Cheers. – nick Jul 31 '14 at 22:23
4

If you were previously calling removeObserver in viewDidUnload/dealloc/deinit, then starting with iOS 9.0 and macOS 10.11, you don't need to call it anymore:

If your app targets iOS 9.0 and later or macOS 10.11 and later, you don't need to unregister an observer in its dealloc method.

source: https://developer.apple.com/documentation/foundation/notificationcenter/1413994-removeobserver

Cœur
  • 37,241
  • 25
  • 195
  • 267