Chapter 22: Cocoa’s Biggest Trick: Key-Value Coding and Observing
There is no magic in Cocoa. It’s just C. But one particular trick borders on “magic,” and that’s key-value observing (KVO). This chapter explores how and when to use KVO, as well as its nonmagical cousin, key-value coding (KVC).
Key-value coding is a mechanism that allows you to access an object’s properties by name rather than by calling explicit accessors. This allows you to determine property bindings at runtime rather than at compile time. For instance, you can request the value of the property named by the string variable
[object valueForKey:someProperty]. You can set the value of the property named by
[object setValue:someValue forKey:someProperty]. This indirection allows you to determine the specific properties to access at runtime rather than at compile time, allowing more flexible and reusable objects. To get this flexibility, your objects need to name their methods in specific ways. This naming convention is called key-value coding, and this chapter covers the rules for creating indirect getters and setters and how to access items in collections and manage KVC with nonobjects. You also find out how to implement advanced KVC techniques such as Higher Order Messaging and collection operators.
If your objects follow the KVC naming rules, then you can also make use of key-value observing. KVO is a mechanism for notifying objects of changes in the properties of other ...