Chapter 15: Cocoa’s Biggest Trick: Key-Value Coding and Observing

There is no magic in Cocoa. It’s just C. But there’s one particular trick that 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 run time rather than at compile time. For instance, you can request the value of the property named by the string variable someProperty using [object valueForKey:someProperty]. You can set the value of someProperty using [object setValue:someValue forKey:someProperty]. This indirection allows you to determine the specific properties to access at run time 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 in this chapter you learn these rules to create indirect getters and setters, access items in collections, and manage KVC with nonobjects. You also learn 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 objects. Cocoa has several ...

Get iOS 5 Programming Pushing the Limits: Developing Extraordinary Mobile Apps for Apple iPhone, iPad, and iPod Touch now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.