Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Key Value Observe removeObserver when observed object is deallocated

There are various questions related to this topic but none of them answer my question.

I want to removeObserver from an object when that object gets deallocated. I am using KVO since multiple items need to be observed, and NSNotification has huge overhead in that case.

Here is the scenario:

(Multiple) Objects are being observed by various other objects. When the observer gets deallocated, I can remove it as an observer. But when the observed get deallocated, I need to tell all the observers to remove themselves as observers. How to do this?

like image 578
Sailesh Avatar asked Jan 31 '12 08:01

Sailesh


2 Answers

Sailesh if the object (observed) get deallocated, then that object can't be altered or it's value cant be changed so if your observers are observing a deallocated object and that deallocated object is never going to send any kind of observation notification then Is there any fun of removing observers???
~~~~~~~~~~~~~~~~~~~~~Edited~~~~~~~~~~~~~~~~~~~~~~~~
hey I got some thing from here. The idea is this you observe an additional property say alive and write in dealloc of observed as alive = NO; and as this property is changed all observer will get notified and thus you can remove all observer.


~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

like image 104
Inder Kumar Rathore Avatar answered Nov 19 '22 13:11

Inder Kumar Rathore


I think there is a design issue here. The observed object should not have to care about it's observers. You say you want to remove the observers from the observed objects dealloc method. But why does it get deallocated? If it's still observed there is an ownership somewhere thus the object will not be dealloced. Good design results in no observers left by the time dealloc is called.

Imagine a view that registers itself as an observer to a model object. This model object is either retained in the view, or in the controller. The model object will not call it's dealloc as long as it's retained somewhere. Only when the last ownership is released, it should call dealloc. So say all ownerships are released, except for the view/viewcontroller and there's one observer left (the view). Now before the view/viewcontroller releases its ownership over the model object, it should also remove the view as an observer. So by the time the dealloc method is called, there should be no observer left.

like image 45
Joris Kluivers Avatar answered Nov 19 '22 14:11

Joris Kluivers