Apple Developer Connection
Member Login Log In | Not a Member? Contact ADC

< Previous PageNext Page > Hide TOC

What is Key-Value Coding?

Key-value coding is a mechanism for accessing an object’s properties indirectly, using strings to identify properties, rather than through invocation of an accessor method or accessing them directly through instance variables.

Key-value coding is an important technique when you are making an application scriptable, and it is a core technology of the binding technologies used by the controller layer. Key-value coding methods can, in many cases, also be utilized to simplify your application’s code.

The essential methods for key-value coding are declared in the NSKeyValueCoding Objective-C informal protocol and the default implementations are provided by NSObject. The method for getting an object’s value is valueForKey:, which returns the value for the property identified by the specified key. The method setValue:forKey: sets the value of the property identified by the specified key.

Key-value coding supports properties that are objects, as well as the scalar data types and structures that are supported by NSNumber and NSValue. Non-object parameters and return types are detected and automatically wrapped, and unwrapped, as required.

The default implementations of setValue:forKey: and valueForKey: attempt to use accessor methods for the specified key. If accessors don’t exist, instance variables can be accessed directly. The complete search implementation is described in “Accessor Search Implementation Details.”

Contents:

Key-Value Coding and Scripting
Using Key-Value Coding to Simplify Your Code
The Named Value Sequence Class


Key-Value Coding and Scripting

The scripting support in Cocoa is designed so an application can easily implement scripting through its model objects. When the user executes an AppleScript command that targets your application, the goal is for that command to go directly to the application’s model objects to get the work done.

Scripting in Mac OS X relies heavily on key-value coding to provide automatic support for executing AppleScript commands. In a scriptable application, a model object defines a set of keys that it supports. Each key represents a property of the model object. Some examples of scripting-related keys are words, font, documents, and color. The key-value coding API provides a generic and automatic way to query an object for the values of its keys and to set new values for those keys.

As you design the objects of your application, you should define the set of keys for your model objects and implement the corresponding accessor methods. Then when you define the script suites for your application, you can specify the keys that each scriptable class supports. If you support key-value coding, you will get a great deal of scripting support “for free.”

In AppleScript, object hierarchies define the structure of the model objects in an application. Most AppleScript commands specify one or more objects within your application by drilling down this object hierarchy from parent container to child element. You can define the relationships between properties available through key-value coding in class descriptions. See “Describing Property Relationships” for more details.

Cocoa’s scripting support takes advantage of key-value coding to get and set information in scriptable objects. The method in the Objective-C informal protocol NSScriptKeyValueCoding and the Java interface NSScriptingKeyValueCoding provide additional capabilities for working with key-value coding, including getting and setting key values by index in multivalue keys and coercing (or converting) a key-value to the appropriate data type.

Using Key-Value Coding to Simplify Your Code

You can use key-value coding methods in your own code to generalize implementations. For example, NSTableView and NSOutlineView objects both associate an identifier string with each of their columns. By making this identifier the same as the key for the property you wish to display, you can significantly simplify your code.

Listing 1 shows an implementation of an NSTableView delegate method without using key-value coding. Listing 2 shows an implementation that takes advantage of key-value coding to return the appropriate value using the column identifier as the key.

Listing 1  Implementation of data-source method without key-value coding

- (id)tableView:(NSTableView *)tableview
      objectValueForTableColumn:(id)column
                            row:(int)row
{
    ChildObject *child = [childrenArray objectAtIndex:row];
    if ( [[column identifier] isEqualToString:@"name"] ) {
        return [child name];
    }
    if ( [[column identifier] isEqualToString:@"age"] ) {
        return [child age];
    }
    if ( [[column identifier] isEqualToString:@"favoriteColor"] ) {
        // etc...
    }
    // etc...
}

Listing 2  Implementation of data-source method with key-value coding

- (id)tableView:(NSTableView *)tableview
      objectValueForTableColumn:(id)column
                            row:(int)row
{
    ChildObject *child = [childrenArray objectAtIndex:row];
    return [child valueForKey:[column identifier]];
}

The Named Value Sequence Class

In addition to key-value coding, the Cocoa frameworks also provide a Java class called NSNamedValueSequence. This class allows you to define a set of keys and assign scalar and object values to them. The class is similar to an NSMutableDictionary, but NSNamedValueSequence is created with a fixed number of elements and it defines convenience methods such as getFloatWithName and setFloatWithName. If you request a value for an undefined key, a default value of zero or nil is returned. After the object reaches its capacity of keys, attempts to define additional keys fail. NSNamedValueSequence objects cannot be resized, nor can keys be deleted.



< Previous PageNext Page > Hide TOC


Last updated: 2007-06-06




Did this document help you?
Yes: Tell us what works for you.

It’s good, but: Report typos, inaccuracies, and so forth.

It wasn’t helpful: Tell us what would have helped.
Get information on Apple products.
Visit the Apple Store online or at retail locations.
1-800-MY-APPLE

Copyright © 2007 Apple Inc.
All rights reserved. | Terms of use | Privacy Notice