Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 255
hyperspasm Avatar asked Jun 06 '11 17:06

hyperspasm


1 Answers

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.

like image 58
Sven Avatar answered Oct 22 '22 04:10

Sven