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:
A public accessor of either the form
keyorgetKey.A private accessor method of either the form
_keyor_getKey.An instance variable named either
keyor_key.Finally, if none of these first three attempts results in anything, the method ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access