In ARC do we need to send removeObserver: explicit

2019-01-24 02:21发布

问题:

Do we have to send removeObserver: explicitly for objects that have been added as observers to an NSNotificationCenter before?

I am bit confused and unable to find the exact answer for this.

Please provide me in detail, about this including why we need to removeObserver explicitly, and why don't compiler put it implicitly in class/application?

回答1:

Yes, you need to call removeObserver:, if you don't the observed class could call all deallocated instance of the observer.



回答2:

From 10.11 observers are not required to un-register in their deallocation method.

NSNotificationCenter and NSDistributedNotificationCenter no longer send notifications to registered observers that may be deallocated. If the observer is able to be stored as a zeroing-weak reference the underlying storage stores the observer as a zeroing weak reference. Alternatively, if the object cannot be stored weakly (because it has a custom retain/release mechanism that would prevent the runtime from being able to store the object weakly) the object is stored as a non-weak zeroing reference. This means that observers are not required to un-register in their deallocation method.[1]



回答3:

Removing the observer is always a smart idea. If you don't remove the observer, messages will still be sent, even if the object was deallocated. It might even be attached to another object, which would definitely lead to serious trouble.



回答4:

You always need to remove observers for KVO as well as for Notifications.