Key - Value Coding

Instance variables are usually set like this,

  anObject.testString = @”a string”;    //or its equivalent
  [anObject setTestString:@"a string"];              

But they can be set by using key-value access,

  [anObject setValue:@"a string" forKey:@"testString"];

The key is the name of the instance variable.

Similarly, the usual way to read an instance variable would be,

  someString = anObject.name;

But it can also be read using key-value access,

  someString = [anObject valueForKey:@”name”];

Why is it useful? The key can be derived dynamically:

  [anObject setValue:@"a string" forKey:theKeyString];

This makes scripting much easier.

In most languages, including C and its cousins, names of variables and routines are used by the compiler to identify things, but they are discarded during linkage and do not appear in the run-time code. Key-value coding keeps the names available at run-time. Apple's documentation is here.

This is very similar to the way one accesses objects in a NSDictionary.

  [aDictionary setObject:someObject forKey:@"keyA"];
  localObject = [aDictionary objectForKey:@"keyA"];

Notice the different method signatures, setObject:forKey: vs. setValue:forKey: and objectForKey: vs. valueForKey:

In a dictionary the key can be an object of any type, though it is conventional to make them NSString. For key-value access the key must be NSString.

Key-Value Observing

The key-value methods can be extended to watch for changes in an instance variable. For example, you have one or more views displaying information from a data source. When that data changes you want to update the views.

Here is a project that demonstrates both.

The page was last updated Thursday, May 3, 2012 2:42 PM