PDA

View Full Version : Key-Value Coding ....a perspective please




mdeh
Mar 24, 2009, 07:05 PM
Key-Value coding is greatly emphasized in Cocoa...well, it is now! :) ( Ch 7 Hillegas and Apple documentation).
But, reading all this, ( Bindings use KVC, make sure your code complies with KVC coding , you can use a string to access the properties of another object, etc etc), I still do not have a feel for what it is **about** KVC that makes it so powerful.

Can anyone take a crack at distilling the essence of KVC.


So, for example, what **can** one do because of KVC that would be really difficult to do without it.
Or..What is it about code that **does** conform to KVC that makes it so much better than code which does not?
Perhaps I am missing something, and that's why I would love to hear from those for whom KVC is so important.

Thanks as always.



kainjow
Mar 24, 2009, 07:44 PM
There's nothing you can do in KVC that you can't do without. It just simplifies and reduces your code.

One example is tables (not dealing with bindings here). Say each column represents a property of your object, with the identifiers properly set. The non-KVC way might be something like this:

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
id myObj = // blah
NSString *identifier = [aTableColumn identifier];
if ([identifier isEqualToString:@"name"])
return [myObj name];
else if ([identifier isEqualToString:@"age"])
return [myObj age];
// etc.

You could replace all that using KVC with this:

- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex {
id myObj = // blah
NSString *identifier = [aTableColumn identifier];
return [myObj valueForKey:identifier];

Another example that comes in handy more often is arrays. Say you have the same objects in an array and you want to get all the names of each object into a new array. The non-KVC way would be to loop through each object, adding its name to the array. The KVC way would be to call valueForKey: on the array, passing @"name", which would do the same thing as the loop.

mdeh
Mar 24, 2009, 08:04 PM
There's nothing you can do in KVC that you can't do without. It just simplifies and reduces your code.

Thanks kainjow

GorillaPaws
Mar 24, 2009, 09:37 PM
Here's a good article (http://www.macresearch.org/cocoa_for_scientists_part_xi_the_value_in_keys) on Key Value Coding.

mdeh
Mar 24, 2009, 10:33 PM
Here's a good article (http://www.macresearch.org/cocoa_for_scientists_part_xi_the_value_in_keys) on Key Value Coding.

good find...thank you....just read it....what I was looking for...thank you again, GorrillaPaws and to Kainjow