Key value Observe removeObserver when an observed object is freed

There are various questions related to this topic, but not one of them answers my question.

I want to removeObserver from an object when this object is freed. I use KVO as I need to observe several elements, and NSNotification has huge overhead in this case.

Here is the scenario:

(Several) Objects are observed by various other objects. When an observer receives an exemption, I can remove it as an observer. But when observed receives exemption, I need to inform all observers in order to remove myself as observers. How to do it?

+6
source share
3 answers

Sailesh, if an object (observable) receives a release, then this object cannot be changed or its value cannot be changed, therefore, if your observers are watching the released object and that the released object will never send any notification about the observation, that is, whether any pleasure in removing observers ???
~~~~~~~~~~~~~~~~~~~~~~~ Edited ~~~~~~~~~~~~~~~~~~~~~~~~ hey hey I got something from here . The idea is that you are observing the additional say alive property and write to the dealloc observable as alive = NO; , and as this property changes, all observers will be notified and therefore you can delete all observers.


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

+3
source

I think there is a design issue here. The observed object does not have to care about these observers. You say you want to remove observers from the dealloc method of observed objects. But why is he freed? If it is still observed, there is ownership somewhere, so the facility will not be canceled. Good design means that by the time dealloc is called, there are no more watchers left.

Imagine a view that registers as an observer for a model object. This model object is stored either in the view or in the controller. The model object will not call it dealloc until it is stored somewhere. Only after the release of the last owner should he call dealloc. Therefore, say that all owners are freed, except for the view / viewcontroller, and there is one observer left (view). Now, before the view / viewcontroller releases its ownership of the model object, it must also remove the view as an observer. Therefore, by the time the dealloc method is called, there should be no observer.

+2
source

You can separately post a notification from -(void)dealloc when the observable is released. upon receipt of all other observers will delete the required notification.

+1
source

Source: https://habr.com/ru/post/907292/


All Articles