When using KVO is it necessary to remove self as an observer of self in -dealloc?

时光毁灭记忆、已成空白 提交于 2019-12-05 23:54:08

问题


in my NSObject subclass's -init method the instance adds itself as an observer of some of its own keyPaths in order to trigger an action that should occur any time one of the properties in question is changed. eg.

[self addObserver:self forKeyPath:@"aProperty" options:0 context:nil];
[self addObserver:self forKeyPath:@"anotherProperty" options:0 context:nil];
...

My question is, in the class's -dealloc method do I necessarily need to remove the instance as an observer of itself? eg.

[self removeObserver:self forKeyPath:@"aProperty"];
[self removeObserver:self forKeyPath:@"anotherProperty"];
...

The way I figure it, when an object tries to send a message to an object that no long exists then an exception gets thrown, clearly a problem. But in this case, an object that doesn't exist anymore couldn't possibly send messages to itself, so this shouldn't be a problem.

I haven't had any issues with this yet, but it does still kind of bother me since I've never seen it explicitly stated that you can do this.

I'm just trying to avoid having to write a whole bunch of

[self removeObserver:self forKeyPath ...]

in my -dealloc method.


回答1:


You probably could get away without removing self as an observer, but you shouldn’t. Where you do addObserver:... you also have to do removeObserver:... later.

But this discussion is irrelevant anyways, because there is no need to observe self, just trigger your action in the setter of your property. This leads to clearer, more readable code that actually performs better.



来源:https://stackoverflow.com/questions/6255757/when-using-kvo-is-it-necessary-to-remove-self-as-an-observer-of-self-in-dealloc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!