Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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
}
...

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top