Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 610
Adam Ernst Avatar asked Aug 09 '09 22:08

Adam Ernst


1 Answers

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.

like image 84
Brian Webster Avatar answered Nov 15 '22 05:11

Brian Webster