- Like Reflection, Sort Of
- Keypaths
- Key Value Observing
- Dependent Keys
- Conclusion
Key Value Observing
In addition to being able to retrieve and set values in a consistent manner, it is also possible to observe values. By registering as an observer, your objects can be notified automatically when a value is changed in an observed object. To observe value1 of our example object, the following method would be called:
[reference addObserver:self forKeyPath:@"value1" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:NULL];
In this example, any time that value1 in the reference object is changed the following method on the calling object will be called:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
The object that is changed along with the key for the value is passed in allowing the calling object to easily process the change. I am sure you are asking yourself about now the same thing I asked: So what? If I call a setter method on an object, I know that I changed it and can react to it. I don't need some observer to tell me that I just changed what I just changed!
That assessment is correct. Being able to observe a change in a value does not have very much use when the program is single-threaded and does not have a GUI. However, when combined with a GUI, being able to observe a value and being notified when that value has changed has a powerful effect. When a GUI is bound to a value in an object using InterfaceBuilder, one of the things InterfaceBuilder does is to set the GUI up as an observer to that value. Now when the value is changed the GUI is automatically updated. This completely eliminates GUI update code because the GUI is always in sync with the underlying data.
This is often referred to as Cocoa Bindings and is considered one of the most powerful features of InterfaceBuilder.