Chapter 7. Key-Value Coding and Key-Value Observing

Key-value coding (or KVC) is a mechanism that allows you to set and get the value of a variable by its name. The name is just a string, but we refer to that name as a key. So, for example, imagine that you have a class called Student that has an instance variable called firstName of type NSString:

@interface Student : NSObject{    NSString *firstName;}...@ends

If you had an instance of Student, you could set its firstName like this:

Student *s = [[Student alloc] init];[s setValue:@"Larry" forKey:@"firstName"];

You could read the value of its firstName like this:

NSString *x = [s valueForKey:@"firstName"];

The methods setValue:forKey: and valueForKey: are defined in NSObject. We know: This doesn’t ...

Get Cocoa® Programming for Mac® OS X, Fourth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.