## 3 Key Value Coding ¶

Key Value Coding is a concept used widely throughout GDL2, it provides a mechanism by where you can access and modify an objects set/accessor methods or even instance variables directly, through a named key.

Additionally some classes may implement KVC in a way specific to the class.

## 4 Setting values through KVC ¶

Setting values through key value coding will try to call a method ’-setKeyName:’ with the value as the parameter to -setKeyName: as a parameter failing that, if anObject had an instance variable with the same name as the key that would be modified directly.

If anObject does not respond to ‘-setKeyName:‘ and there is no instance variable with the same name as the key, an exception is thrown.

    [anObject setValue:@"bar" forKey:@"foo"];

Will first try to call -setFoo: then attempt to set the instance variable named "foo" to "bar".

## 5 Accessing values through KVC ¶

Accessing values through Key Value Coding first attempts to call the -keyName method on anObject if it responds. If the object does not respond then it will try to access an instance variable with the name of the key.

If there is no method or instance variable with the name of the key an exception will be thrown.

For example,

    [anObject valueForKey:@"foo"];

Will first try to call -foo, then attempt to return instance variable named foo.

## 6 Key Paths ¶

Key paths are a list of keys separated by a dot.

The first key accesses the key on the target object through normal KVC, and each subsequent key is sent to the object returned through the previous key in the list.

For example,

    [anObject valueForKeyPath:@"foo.bar"];

Will be equivalent to

    [[anObject valueForKey:@"foo"] valueForKey:@"bar"];

## 7 Type promotion ¶

When a accessing a key, you may access keys for things such as standard c numerical types, and they will be automatically promoted to their object equivalent

For example:

    [@"foo" valueForKey:@"length"];

Returns a NSNumber object containing ’3’.

## 8 Class specific implementation ¶

By implementing valueForKey: and setValueForKey: classes can implement functionality to contain keys in an instance variable such as a dictionary, but they can also implement something to work on a collection of objects.

For instance NSArray implements KVC to forward key value coding to all objects in the array.

Suppose we have an array contain a few string objects.

    ("Example", "array", "containing", "strings")

If we get the value for the key length, it will return an NSArray of NSNumbers

    (7, 5, 10, 7).