view raw
Honey Honey - 7 months ago 56
iOS Question

why do you have to remove observer in ios8?

After reading this post for iOS 9, I know that you don't need to removeObserver anymore.

However for iOS 8, you needed to removeObserver in the

method of the viewController.
But I can't make sense of it. If a viewController is deallocated then it's DEAD isn't? Why do we need to do a removeObserver. It being an observer is much like calling a dead person who will never pick up the phone

What am I not understanding?


It's fully explained in the article you linked:

The notification center now keeps a zeroing reference to the observer:

If the observer is able to be stored as a zeroing-weak reference the underlying storage will store the observer as a zeroing weak reference, alternatively if the object cannot be stored weakly (i.e. it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) it will store the object as a non-weak zeroing reference.

Prior to iOS 9, NSNotificationCenter wasn't implemented using a weak reference so NSNotificationCenter didn't know the target had been deallocated. It blindly sent notifications to any target that had been registered. This is bad (likely crash) if the target has been deallocated. Hence the need to always unregister.

In iOS 9, NSNotificationCenter started using weak references. This means it now knows if one of the registered targets has been deallocated or not. This means it no longer attempts to send notifications to deallocated targets. And this means you no longer need to explicitly unregister the target before it is deallocated.