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

Next Page > Hide TOC

NSKeyValueCoding Protocol Reference

(informal protocol)

Framework
/System/Library/Frameworks/Foundation.framework
Companion guide
Declared in
NSKeyValueCoding.h

Overview

The NSKeyValueCoding informal protocol defines a mechanism by which you can access the properties of an object indirectly by name (or key), rather than directly through invocation of an accessor method or as instance variables. Thus, all of an object’s properties can be accessed in a consistent manner.

The basic methods for accessing an object’s values are setValue:forKey:, which sets the value for the property identified by the specified key, and valueForKey:, which returns the value for the property identified by the specified key. The default implementation uses the accessor methods normally implemented by objects (or to access instance variables directly if need be).

Tasks

Getting Values

Setting Values

Changing Default Behavior

Validation

Deprecated Methods

Class Methods

accessInstanceVariablesDirectly

Returns a Boolean value that indicates whether the key-value coding methods should access the corresponding instance variable directly on finding no accessor method for a property.

+ (BOOL)accessInstanceVariablesDirectly

Return Value

YES if the key-value coding methods should access the corresponding instance variable directly on finding no accessor method for a property, otherwise NO.

Discussion

The default returns YES. Subclasses can override it to return NO, in which case the key-value coding methods won’t access instance variables.

Availability
Declared In
NSKeyValueCoding.h

useStoredAccessor

Returns YES if the stored value methods storedValueForKey: and takeStoredValue:forKey: should use private accessor methods in preference to public accessors. (Deprecated. This method has no direct replacement, although see accessInstanceVariablesDirectly.)

+ (BOOL)useStoredAccessor

Discussion

Returning NO causes the stored value methods to use the same accessor method or instance variable search order as the corresponding basic key-value coding methods (valueForKey: and takeValue:forKey:). The default implementation returns YES.

Applications should use the valueForKey: and setValue:forKey: methods instead of storedValueForKey: and takeStoredValue:forKey:.

Availability
Declared In
NSKeyValueCoding.h

Instance Methods

dictionaryWithValuesForKeys:

Returns a dictionary containing the property values identified by each of the keys in a given array.

- (NSDictionary *)dictionaryWithValuesForKeys:(NSArray *)keys

Parameters
keys

An array containing NSString objects that identify properties of the receiver.

Return Value

A dictionary containing as keys the property names in keys, with corresponding values being the corresponding property values.

Discussion

The default implementation invokes valueForKey: for each key in keys and substitutes NSNull values in the dictionary for returned nil values.

Availability
See Also
Declared In
NSKeyValueCoding.h

handleQueryWithUnboundKey:

Invoked by valueForKey: when it finds no property corresponding to key. (Deprecated. Use valueForUndefinedKey: instead.)

- (id)handleQueryWithUnboundKey:(NSString *)key

Availability
Declared In
NSKeyValueCoding.h

handleTakeValue:forUnboundKey:

Invoked by takeValue:forKey: when it finds no property binding for key. (Deprecated. Use setValue:forUndefinedKey: instead.)

- (void)handleTakeValue:(id)value forUnboundKey:(NSString *)key

Availability
Declared In
NSKeyValueCoding.h

mutableArrayValueForKey:

Returns a mutable array that provides read-write access to an ordered to-many relationship specified by a given key.

- (NSMutableArray *)mutableArrayValueForKey:(NSString *)key

Parameters
key

The name of an ordered to-many relationship.

Return Value

A mutable array that provides read-write access to the ordered to-many relationship specified by key.

Discussion

Objects added to the mutable array become related to the receiver, and objects removed from the mutable array become unrelated. The default implementation recognizes the same simple accessor methods and array accessor methods as valueForKey:, and follows the same direct instance variable access policies, but always returns a mutable collection proxy object instead of the immutable collection that valueForKey: would return.

This method also:

  1. Searches the class of the receiver for a pair of methods whose names match the patterns insertObject:in<Key>AtIndex: and removeObjectFrom<Key>AtIndex: (and therefore correspond to the two most primitive methods defined by the NSMutableArray class). If both methods are found, each NSMutableArray message sent to the collection proxy object results in some combination of insertObject:in<Key>AtIndex: and removeObjectFrom<Key>AtIndex: messages being sent to the original receiver of mutableArrayValueForKey:, unless the class of the receiver also implements an optional method whose name matches the pattern replaceObjectIn<Key>AtIndex:withObject:, in which case that replacement method will be used when appropriate for best performance.

  2. Otherwise (no set of mutable array primitive methods is found), searches the class of the receiver for an accessor method whose name matches the pattern set<Key>:. If such a method is found, each NSMutableArray message sent to the collection proxy object results in a set<Key>: message being sent to the original receiver of mutableArrayValueForKey:.

  3. Otherwise (no set of mutable array primitive methods or simple accessor method is found), if the receiver's accessInstanceVariablesDirectly class method returns YES, searches the class of the receiver for an instance variable whose name matches the pattern _<key> or <key>, in that order. If such an instance variable is found, each NSMutableArray message sent to the collection proxy object will be forwarded to the instance variable's value, which therefore must typically be an instance of NSMutableArray or a subclass of NSMutableArray.

  4. Otherwise (no set of mutable array primitives, simple accessor method, or instance variable is found), raises an NSUndefinedKeyException.

Availability
See Also
Declared In
NSKeyValueCoding.h

mutableArrayValueForKeyPath:

Returns a mutable array that provides read-write access to the ordered to-many relationship specified by a given key path.

- (NSMutableArray *)mutableArrayValueForKeyPath:(NSString *)keyPath

Parameters
keyPath

A key path, relative to the receiver, to an ordered to-many relationship.

Return Value

A mutable array that provides read-write access to the ordered to-many relationship specified by keyPath.

Discussion

See mutableArrayValueForKey: for additional details.

Availability
See Also
Declared In
NSKeyValueCoding.h

mutableSetValueForKey:

Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key.

- (NSMutableSet *)mutableSetValueForKey:(NSString *)key

Parameters
key

The name of an unordered to-many relationship.

Return Value

A mutable set that provides read-write access to the unordered to-many relationship specified by key.

Discussion

Objects added to the mutable set become related to the receiver, and objects removed from the mutable set become unrelated. The default implementation recognizes the same simple accessor methods and set accessor methods as valueForKey:, and follows the same direct instance variable access policies, but always returns a mutable collection proxy object instead of the immutable collection that valueForKey: would return.

This method also:

  1. Searches the class of the receiver for a pair of methods whose names match the patterns add<Key>Object: and remove<Key>Object: (and therefore correspond to the two most primitive methods defined by the NSMutableSet class) and also add<Key>: and remove<Key>: (and therefore corresponding NSMutableSet’s unionSet: and minusSet:). If at least one addition method and at least one removal method are found each NSMutableSet message sent to the collection proxy object will result in some combination of add<Key>Object:, remove<Key>Object:, add<Key>:, and remove<Key>: messages being sent to the original receiver of mutableSetValueForKey:. If the receiver also implements an optional method whose name matches the pattern intersect<Key>: or set<Key>: that method will be used when appropriate for best performance.

  2. Otherwise (no set of set mutation methods is found), searches the class of the receiver for an accessor method whose name matches the pattern set<Key>:. If such a method is found, each NSMutableSet message sent to the collection proxy object results in a set<Key>: message being sent to the original receiver of mutableSetValueForKey:.

  3. Otherwise (no set of set mutation methods or simple accessor method is found), if the receiver's accessInstanceVariablesDirectly class method returns YES, searches the class of the receiver for an instance variable whose name matches the pattern _<key> or <key>, in that order. If such an instance variable is found, each NSMutableSet message sent to the collection proxy object will be forwarded to the instance variable's value, which therefore must typically be an instance of NSMutableSet or a subclass of NSMutableSet.

  4. Otherwise (no set of mutable array primitives, simple accessor method, or instance variable is found), raises an NSUndefinedKeyException.

Note: The repetitive set<Key>: messages implied by Step 2's description are a potential performance problem. For better performance implement methods that fulfill the requirements for Step 1 in your KVC-compliant class.

Availability
See Also
Declared In
NSKeyValueCoding.h

mutableSetValueForKeyPath:

Returns a mutable set that provides read-write access to the unordered to-many relationship specified by a given key path.

- (NSMutableSet *)mutableSetValueForKeyPath:(NSString *)keyPath

Parameters
keyPath

A key path, relative to the receiver, to an unordered to-many relationship.

Return Value

A mutable set that provides read-write access to the unordered to-many relationship specified by keyPath.

Discussion

See mutableSetValueForKey: for additional details.

Availability
See Also
Declared In
NSKeyValueCoding.h

setNilValueForKey:

Invoked by setValue:forKey: when it’s given a nil value for a scalar value (such as an int or float).

- (void)setNilValueForKey:(NSString *)key

Parameters
key

The name of one of the receiver's properties.

Discussion

Subclasses can override this method to handle the request in some other way, such as by substituting 0 or a sentinel value for nil and invoking setValue:forKey: again or setting the variable directly. The default implementation raises an NSInvalidArgumentException.

Availability
Declared In
NSKeyValueCoding.h

setValue:forKey:

Sets the property of the receiver specified by a given key to a given value.

- (void)setValue:(id)value forKey:(NSString *)key

Parameters
value

The value for the property identified by key.

key

The name of one of the receiver's properties.

Discussion

If key identifies a to-one relationship, relate the object specified by value to the receiver, unrelating the previously related object if there was one. Given a collection object and a key that identifies a to-many relationship, relate the objects contained in the collection to the receiver, unrelating previously related objects if there were any.

The default implementation of this method does the following:

  1. Searches the class of the receiver for an accessor method whose name matches the pattern -set<Key>:. If such a method is found the type of its parameter is checked. If the parameter type is one of the data types supported by NSNumber or NSValue but the value is nil, setNilValueForKey: is invoked. If the value is not nil the appropriate -<type>Value: message is sent to the value and the result is used as the argument of an invocation of the accessor method. If the type of the accessor method's parameter is not an NSNumber or NSValue data type the accessor method is invoked with value as the argument.

  2. Otherwise (no accessor method is found), if the receiver's accessInstanceVariablesDirectly class method returns YES, searches the class of the receiver for an instance variable whose name matches the pattern _<key>, _is<Key>, <key>, or is<Key>, in that order. If such an instance variable is found and its type is an NSNumber or NSValue data type, the value of the instance variable in the receiver is set using the same conversion as in step 1. If such an instance variable is found but its type is not an NSNumber or NSValue data type, the value is retained and the result is set in the instance variable, after first autoreleasing the instance variable's old value.

  3. Otherwise (no accessor method or instance variable is found), invokes setValue:forUndefinedKey:.

Compatibility notes:

Note:  When the receiver is an instance of a Java class, member functions whose names match the pattern set<Key>() will be recognized in step 1.

Availability
Declared In
NSKeyValueCoding.h

setValue:forKeyPath:

Sets the value for the property identified by a given key path to a given value.

- (void)setValue:(id)value forKeyPath:(NSString *)keyPath

Parameters
value

The value for the property identified by keyPath.

keyPath

A key path of the form relationship.property (with one or more relationships): for example “department.name” or “department.manager.lastName.”

Discussion

The default implementation of this method gets the destination object for each relationship using valueForKey:, and sends the final object a setValue:forKey: message.

Availability
See Also
Declared In
NSKeyValueCoding.h

setValue:forUndefinedKey:

Invoked by setValue:forKey: when it finds no property for a given key.

- (void)setValue:(id)value forUndefinedKey:(NSString *)key

Parameters
value

The value for the key identified by key.

key

A string that is not equal to the name of any of the receiver's properties.

Discussion

Subclasses can override this method to handle the request in some other way. The default implementation raises an NSUndefinedKeyException.

Availability
See Also
Declared In
NSKeyValueCoding.h

setValuesForKeysWithDictionary:

Sets properties of the receiver with values from a given dictionary, using its keys to identify the properties.

- (void)setValuesForKeysWithDictionary:(NSDictionary *)keyedValues

Parameters
keyedValues

A dictionary whose keys identify properties in the receiver. The values of the properties in the receiver are set to the corresponding values in the dictionary.

Discussion

The default implementation invokes setValue:forKey: for each key-value pair, substituting nil for NSNull values in keyedValues.

Availability
See Also
Declared In
NSKeyValueCoding.h

storedValueForKey:

Returns the property identified by a given key. (Deprecated. If you are using the NSManagedObject class, use primitiveValueForKey: instead.)

- (id)storedValueForKey:(NSString *)key

Discussion

This method is used when the value is retrieved for storage in an object store (generally, this storage is ultimately in a database) or for inclusion in a snapshot. The default implementation is similar to the implementation of valueForKey:, but it resolves key with a different method/instance variable search order:

  1. Searches for a private accessor method based on key (a method preceded by an underbar). For example, with a key of “lastName”, storedValueForKey: looks for a method named _getLastName or _lastName.

  2. If a private accessor is not found, searches for an instance variable based on key and returns its value directly. For example, with a key of “lastName”, storedValueForKey: looks for an instance variable named _lastName or lastName.

  3. If neither a private accessor nor an instance variable is found, storedValueForKey: searches for a public accessor method based on key. For the key “lastName”, this would be getLastName or lastName.

  4. If key is unknown, storedValueForKey: calls handleTakeValue:forUnboundKey:.

This different search order allows an object to bypass processing that is performed before returning a value through a public API. However, if you always want to use the search order in valueForKey:, you can implement the class method useStoredAccessor to return NO. And as with valueForKey:, you can prevent direct access of an instance variable with the class method accessInstanceVariablesDirectly.

Availability
Declared In
NSKeyValueCoding.h

unableToSetNilForKey:

Invoked if key is represented by a scalar attribute. (Deprecated. Use setNilValueForKey: instead.)

- (void)unableToSetNilForKey:(NSString *)key

Availability
Declared In
NSKeyValueCoding.h

validateValue:forKey:error:

Returns a Boolean value that indicates whether the value specified by a given pointer is valid for the property identified by a given key.

- (BOOL)validateValue:(id *)ioValue forKey:(NSString *)key error:(NSError **)outError

Parameters
ioValue

A pointer to a new value for the property identified by key. This method may modify or replace the value in order to make it valid.

key

The name of one of the receiver's properties. The key must specify an attribute or a to-one relationship.

outError

If validation is necessary and ioValue is not transformed into a valid value, upon return contains an NSError object that describes the reason that ioValue is not a valid value.

Return Value

YES if *ioValue is a valid value for the property identified by key, or of the method is able to modify the value to *ioValue to make it valid; otherwise NO.

Discussion

The default implementation of this method searches the class of the receiver for a validation method whose name matches the pattern validate<Key>:error:. If such a method is found it is invoked and the result is returned. If no such method is found, YES is returned.

The sender of the message is never given responsibility for releasing ioValue or outError.

See “Key-Value Validation” for more information.

Availability
See Also
Declared In
NSKeyValueCoding.h

validateValue:forKeyPath:error:

Returns a Boolean value that indicates whether the value specified by a given pointer is valid for a given key path relative to the receiver.

- (BOOL)validateValue:(id *)ioValue forKeyPath:(NSString *)inKeyPath error:(NSError **)outError

Parameters
ioValue

A pointer to a new value for the property identified by keyPath. This method may modify or replace the value in order to make it valid.

key

The name of one of the receiver's properties. The key path must specify an attribute or a to-one relationship. The key path has the form relationship.property (with one or more relationships); for example “department.name” or “department.manager.lastName”.

outError

If validation is necessary and ioValue is not transformed into a valid value, upon return contains an NSError object that describes the reason that ioValue is not a valid value.

Discussion

The default implementation gets the destination object for each relationship using valueForKey: and returns the result of a validateValue:forKey:error: message to the final object.

Availability
See Also
Declared In
NSKeyValueCoding.h

valueForKey:

Returns the value for the property identified by a given key.

- (id)valueForKey:(NSString *)key

Parameters
key

The name of one of the receiver's properties.

Return Value

The value for the property identified by key.

Discussion

The default implementation works as follows:

  1. Searches for a public accessor method based on key. For example, with a key of “lastName”, valueForKey: looks for a method named getLastName or lastName.

  2. If a public accessor method is not found and the class method accessInstanceVariablesDirectly returns YES, searches for a private accessor method based on key (a method preceded by an underbar). For example, with a key of “lastName”, valueForKey: looks for a method named _getLastName or _lastName.

  3. If an accessor method is not found valueForKey: searches for an instance variable based on key and returns its value directly. For the key “lastName”, this would be _lastName or lastName.

  4. If neither an accessor method nor an instance variable is found, the default implementation invokes valueForUndefinedKey:.

Availability
Declared In
NSKeyValueCoding.h

valueForKeyPath:

Returns the value for the derived property identified by a given key path.

- (id)valueForKeyPath:(NSString *)keyPath

Parameters
keyPath

A key path of the form relationship.property (with one or more relationships); for example “department.name” or “department.manager.lastName”.

Return Value

The value for the derived property identified by keyPath.

Discussion

The default implementation gets the destination object for each relationship using valueForKey: and returns the result of a valueForKey: message to the final object.

Availability
See Also
Declared In
NSKeyValueCoding.h

valueForUndefinedKey:

Invoked by valueForKey: when it finds no property corresponding to a given key.

- (id)valueForUndefinedKey:(NSString *)key

Parameters
key

A string that is not equal to the name of any of the receiver's properties.

Discussion

Subclasses can override this method to return an alternate value for undefined keys. The default implementation raises an NSUndefinedKeyException.

Availability
See Also
Declared In
NSKeyValueCoding.h

Constants

Key Value Coding Exception Names

This constant defines the name of an exception raised when a key value coding operation fails.

extern NSString *NSUndefinedKeyException;

Constants
NSUndefinedKeyException

Raised when a key value coding operation fails. userInfo keys are described in “NSUndefinedKeyException userInfo Keys”

Available in Mac OS X v10.3 and later.

Declared in NSKeyValueCoding.h

Declared In
NSKeyValueCoding.h

NSUndefinedKeyException userInfo Keys

These constants are keys into an NSUndefinedKeyException userInfo dictionary

extern NSString *NSTargetObjectUserInfoKey;
extern NSString *NSUnknownUserInfoKey;

Constants
NSTargetObjectUserInfoKey

The object on which the key value coding operation failed.

NSUnknownUserInfoKey

The key for which the key value coding operation failed.

Discussion

For additional information see “Key Value Coding Exception Names.”

Declared In
NSKeyValueCoding.h

Array operators

These constants define the available array operators. See Set and Array Operators for more information.

NSString *const NSAverageKeyValueOperator;
NSString *const NSCountKeyValueOperator;
NSString *const NSDistinctUnionOfArraysKeyValueOperator;
NSString *const NSDistinctUnionOfObjectsKeyValueOperator;
NSString *const NSDistinctUnionOfSetsKeyValueOperator;
NSString *const NSMaximumKeyValueOperator;
NSString *const NSMinimumKeyValueOperator;
NSString *const NSSumKeyValueOperator;
NSString *const NSUnionOfArraysKeyValueOperator;
NSString *const NSUnionOfObjectsKeyValueOperator;
NSString *const NSUnionOfSetsKeyValueOperator;

Constants
NSAverageKeyValueOperator

The @avg array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSCountKeyValueOperator

The @count array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSDistinctUnionOfArraysKeyValueOperator

The @distinctUnionOfArrays array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSDistinctUnionOfObjectsKeyValueOperator

The @distinctUnionOfObjects array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSDistinctUnionOfSetsKeyValueOperator

The @distinctUnionOfSets array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSMaximumKeyValueOperator

The @max array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSMinimumKeyValueOperator

The @min array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSSumKeyValueOperator

The @sum array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSUnionOfArraysKeyValueOperator

The @unionOfArrays array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSUnionOfObjectsKeyValueOperator

The @unionOfObjects array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

NSUnionOfSetsKeyValueOperator

The @unionOfSets array operator.

Available in Mac OS X v10.4 and later.

Declared in NSKeyValueCoding.h

Availability
Declared In
NSKeyValueCoding.h

Next Page > Hide TOC


Last updated: 2007-02-23




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