Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
435 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...