O'Reilly logo

Cocoa in a Nutshell by James Duncan Davidson, Michael Beam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Key-Value Coding

Key-value coding lets you access the properties of an object (such as the instance variables) indirectly by using strings referred to as keys . Although key-value coding can access instance variables directly, it first tries to use accessor methods to access a property. However, accessor methods are not necessarily mapped to instance variables, which means that an accessor may provide a property value that is computed (perhaps from instance variables).

Key-value coding is a powerful feature of Cocoa that forms the basis of many important technologies. For example, Cocoa’s scripting capability is heavily based on the functionality of key-value coding.

The methods that provide an interface to key-value coding are declared in the Foundation framework’s NSKeyValueCoding protocol. The principal methods are valueForKey: and takeValue:forKey:, which get and set the instance variable associated with the specified key. NSObject provides default implementations of the methods of NSKeyValueCoding. These default implementations associate keys with instance variables based on a simple set of rules. The methods that return a value, valueForKey: for instance, attempt to access the property specified by the string @"key" using the following means:

  1. A public accessor of either the form key or getKey.

  2. A private accessor method of either the form _key or _getKey.

  3. An instance variable named either key or _key.

  4. Finally, if none of these first three attempts results in anything, the method ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required