2008 04 22Key Value Bastard Observing
Key Value Bastard Observing (KVBO) is a technique to observe changes to all keys of all instances of a class. If you've ever written code to observe a collection, adding observers to newly created objects, removing deleted object's observers, adding another observer for that one more key you need to check, … KVBO will save you time and aspirin.
Making a class KVBO compliant
We'll make a class called SampleObject KVBO compliant.
- Overload
setValue:forKey:
to listen to all changes - Save
self
and the key name (fromforKey:
) with a class method calledsetLastModifiedKey:forInstance:
. They will be stored as static variables and will be read by KVBO observers -
setValue:forKey:
then sets a new value for a dummy key (keyChanged) on a shared instance (a singleton for the observed class, here SampleObject). Changing this dummy key's value dispatches KVO notifications of our shared instance
From here, an observer listening to the shared instance will receive notifications of all changes to all instances of SampleObject and be able to see which key of which instance changed.
Listening to KVBO
You can listen using 2 methods :
- standard KVO : use
addObserver:forKeyPath:options:context:
to listen to your KVBO class' shared instance. All notifications will go through the KVO methodobserveValueForKeyPath:ofObject:change:context:
- bindings : use
bind:toObject:withKeyPath:options:
to bind the shared instance to an observer. All notifications will go through the set method of the key you bind to
Which one to use ? That's a matter of taste. Using standard KVO, you have a fixed name method (addObserver:forKeyPath:options:context:
) to receive all notifications. Using bindings, you get to choose the name of your method, but it has to start with set.