Leveraging key-value observing
Key-value observing, generally abbreviated in literature to KVO, is a mechanism by which an object can observe properties of another object, so that when, for example, the data in your data model changes, that change is automatically reflected in the user interface. There are different ways for objects to notify one another in Cocoa; KVO, which is used for a number of purposes within Cocoa itself, including Cocoa bindings, Core Data, and AppleScript support, is a well-established pattern.
It doesn't take a huge amount of effort to set up, and does save you a fair amount of repetitive boilerplate code writing.
Coding for KVO
There are three steps involved in setting up KVO, and one cleanup step when we have finished observing:
- We need to prepare our classes for KVO.
- We need to let the system know when we wish to observe an object, and which change(s) we wish to observe.
- We need to override NSObject's method that handles the change notification.
And when we are done...