Adam Ernst
Adam Ernst

Reputation: 54060

Observing self in Cocoa

In Cocoa, addObserver:forKeyPath:options:context: retains "neither the receiver, nor anObserver". Therefore I assume observing self is allowed; that is, it's perfectly valid to do something like

[self addObserver:self forKeyPath...]

As long as you remember to unregister self as an observer as the first thing in dealloc.

Is this assumption correct?

Upvotes: 5

Views: 3729

Answers (3)

user23743
user23743

Reputation:

Don't remove an observer in -dealloc. Why? Because when you turn on the garbage collector things will stop working; -dealloc never gets called. You should just use the -dealloc and -finalize methods for memory-related cleanup code.

Upvotes: -1

Benedict Cohen
Benedict Cohen

Reputation: 11920

I do what Brian Webster said. Here's an example:

//.h
...
@property(readwrite, retain, setter=setMyPropertySynth:) id myProperty;
-(void)setMyProperty:(id)newValue;
....


//.m
...
@synthesize myProperty;

-(void)setMyProperty:(id)newValue
{
    //add code here

    [self setMyPropertySynth:newValue];

    //add more code here
}
...

Upvotes: 1

Brian Webster
Brian Webster

Reputation: 12045

Yes, there is not really any reason you can't observe self. But like you said, like any KVO observation, make sure to remove yourself as an observer before being dealloced.

For the record, one alternate way of doing this if you're just talking about a simple key is to write a custom setter and execute whatever code you need in the setter. This style makes it a little more obvious what the full effects of calling the setter are. The KVO way is a bit more flexible though, and works with key paths that contain multiple components.

Upvotes: 12

Related Questions