Objective-C Language Most Common Real Life Key Value Coding Example


Example

Key Value Coding is integrated into NSObject using NSKeyValueCoding protocol.

What this means?

It means that any id object is capable of calling valueForKey method and its various variants like valueForKeyPath etc. '

It also means that any id object can invoke setValue method and its various variants too.

Example:

id obj = [[MyClass alloc] init];
id value = [obj valueForKey:@"myNumber"];

int myNumberAsInt = [value intValue];
myNumberAsInt = 53;
[obj setValue:@(myNumberAsInt) forKey:@"myNumber"];

Exceptions:

Above example assumes that MyClass has an NSNumber Property called myNumber. If myNumber does not appear in MyClass interface definition, an NSUndefinedKeyException can be raised at possibly both lines 2 and 5 - popularly known as:

this class is not key value coding-compliant for the key myNumber.

Why this is SO powerful:

You can write code that can access properties of a class dynamically, without needing interface for that class. This means that a table view can display values from any properties of an NSObject derived object, provided its property names are supplied dynamically at runtime.

In the example above, the code can as well work without MyClass being available and id type obj being available to calling code.