why do you have to remove observer in ios8?

2019-02-10 16:36发布

问题:

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 deinit 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?

回答1:

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.



回答2:

It being an observer is much like calling a dead person who will never pick up the phone

Exactly!

Your phone number in this case is a memory address, which will be dereferenced once the notification center tries to call the observer. Now, what do you expect to be at this memory address once the View Controller has been deallocated? We can’t know.

But you certainly don’t want to call a method (that’s what the notification center does) on an object which might not be there anymore or even have been replaced by something completely different (an image for instance).

To add a real world example: It’s more like relying on that your car (the view controller) is at a specific place in the garage (the memory address). You absolutely rely on your car to be there, so you don’t even look if it’s there when you want to get in. Now, pretend somebody removed (deallocated) your car, but you still rely on it being there. It’ll surely be a painful experience to get into and sit down in a car that is no longer there.