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

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

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

-nick

+8
swift nsnotificationcenter
source share
1 answer

It really depends on the role of the class in which you subscribe to NSNotificationCenter notifications. If you subscribed to:

Uiview

Then you must unsubscribe as soon as the view becomes invisible to the user. To save processor cycles and not consume resources until the user sees the view.

UIViewController

It also depends on the action you are about to take in response to the notification. If this is just a user interface setup, you should unsubscribe as soon as the view controller disappears from the screen.

Your application service level

It is okay to have a .removeObserver inside deinit (). however, even here I am inclined to offer you more details about when you sign up and unsubscribe from NSNotificationCenter notifications and put them in the methods of starting and stopping your service.

+10
source share

All Articles