Key Value Observing Improvements v1.2
Hot on the heels of the 1.1 bug fix release comes version a freshly rewritten 1.2 with API cleanup, bug fixes, and a great new feature.
Lately, I've been using observers to allow an object to observe changes to its own properties. This means I don't have to override the setter method (I'm using synthesized properties) and the observation is managed the same way that it would be externally. The current KVO implementation (at least, in non-GC land,) however, doesn't allow you to remove observations from yourself in your -dealloc method. This is due to the way KVO works, by interposing a KVODeallocate function before your -dealloc method. It expects that all observers of the object have been removed at this point, and warns if they are not. This is, of course, blindingly annoying -- you now have to create a method that gets called on your objects by their owner before they dealloc so that they can remove their observers.
To fix this, I've done a little interposing of my own, putting in another dealloc method before KVODealloc that will remove self observers and call a -KVODealloc method on the deallocating observer object before KVODeallocate is called. If you don't want automatic removal, simply return NO from +automaticallyRemoveSelfObservations on the class of your choice.
The new updates are in SVN at
http://svn.shiftedbits.org/public/KVOAdditions/trunk and tagged at
Version 1.2 also adds new methods for removing an observer that include a selector parameter.
- (void)removeObserver:(NSObject *)observer forKeyPath:(NSString *)keyPath selector:(SEL)selector;
- (void)removeObserver:(NSObject *)observer fromObjectsAtIndexes:(NSIndexSet *)indexes forKeyPath:(NSString *)keyPath selector:(SEL)selector;
The selector is now considered a unique part of the observation, and so a class can observe a single property on a single object using multiple selectors. This allows a class and its subclass to avoid collisions when observing a single object.
-removeObserver:forKeyPath: method now no longer removes selector-based observers.
Rob Napier at 2008-09-20 22:39:14 -0400
This category is really incredible. I came across it looking for a solution to the dealloc problem, and it's immediately fixed several other KVO concerns. Thank you. Is there any mailing list for svn updates?
Devin Lane at 2008-09-20 22:47:30 -0400
Glad you find it useful. I don't have a mailing list set up, I'm thinking it's small enough that I'll just announce updates on the blog.