Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ARC do we need to send removeObserver: explicitly?

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?

like image 784
Anoop Vaidya Avatar asked Dec 17 '12 09:12

Anoop Vaidya


3 Answers

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

like image 82
rckoenes Avatar answered Oct 20 '22 14:10

rckoenes


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]

like image 8
Parag Bafna Avatar answered Oct 20 '22 13:10

Parag Bafna


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.

like image 5
IluTov Avatar answered Oct 20 '22 14:10

IluTov