Strictly Programming

Cocoa Binding – Key Value Coding

Posted in Objective-C, Uncategorized by sqllyw on 05/26/2010

KVC is similar to Java’s beans.

KVC is the basis for the binding mechanism to work in Cocoa.

here is a sample class:

@interface Person : NSObject {
	NSString *name;
	float age;
	BOOL isMarried;

You can create an object of Person and set the attributes as follow:

	Person *me = [Person alloc];
	[me setValue:@"John" forKey:@"name"];
	[me setValue:[NSNumber numberWithFloat:1.5] forKey:@"age"];
	[me setValue:[NSNumber numberWithBool:NO] forKey:@"isMarried"];

To access the values:

	NSLog(@" my name is %@", [me valueForKey:@"name"]);

This is very similar to Java’s beans, however bean requires you to write a getter/setter while KVC does not. of course you can also provide getter/setter in KVC, if it is provided, Cocoa will use that instead of its internal method(getValue/setValue):

	provide getter/setter sample code.

In Objective C 2.0, we have another way to specify getter/setter, it is very similar to Java/Tapestry 5’s annotation:

private String name;

Java does not have header, you specify @property in only one place while in Objective C, you need to do this in two places, one in .h and another in .m:

header sample
m sample

The point here is, neither getter/setter nor @property annotation is required to have KVC working in your code. the getValue/setValue from NSObject will make sure the KVC is working.

Tagged with: , ,

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: