Stuntman And Lover Of Cheese

by Dan Bostonweeks

Square Signals : KVO+Blocks: Block Callbacks for Cocoa Observers

Square Signals : KVO+Blocks: Block Callbacks for Cocoa Observers: “Andy Matuschak.

Panther introduced Key-Value Observing, a Cocoa implementation of the observer pattern. It’s very useful, but the API kind of sucks. To get observation notices, you have to override a lengthy selector (observeValueForKeyPath:ofObject:change:context:), provide a static context pointer, and essentially implement a big switch statement on the key path. That’s unwieldy, but I think it also makes for unmaintainable code: the callbacks end up thrown in the same method, and they’re separated from the observer registration. KVO+Blocks is an NSObject category I wrote which provides addObserverForKeyPath:task:, where the latter parameter is a block.