Most Common Real Life Key Value Coding Example

suggest change

Key Value Coding is integrated into NSObject using NSKeyValueCoding protocol.

What does this mean?

Any object can be sent valueForKey: and its variants, such as valueForKeyPath:. It can also be sent setValue:forKey: and that method’s variants. Not every object is compliant for every key.

Example:

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

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

Exceptions:

The example assumes that MyClass has an NSNumber property named myNumber. If it does not, valueForKey: and setValue:forKey: can raise NSUndefinedKeyException. The exception reason looks like:

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

Why this is SO powerful:

You can access properties by name at runtime, without a compile-time declaration of those properties. A table view can display values from an NSObject subclass when the property names are supplied dynamically.

The caller needs the key names. It does not need a static type more specific than id.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents