In ARC do we need to send removeObserver: explicit

2019-01-24 02:10发布

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?

4条回答
冷血范
2楼-- · 2019-01-24 02:18

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.

查看更多
我只想做你的唯一
3楼-- · 2019-01-24 02:27

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

查看更多
Ridiculous、
4楼-- · 2019-01-24 02:43

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

查看更多
冷血范
5楼-- · 2019-01-24 02:43

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]

查看更多
登录 后发表回答