Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

mdeh

macrumors 6502
Original poster
Jan 3, 2009
345
2
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

Moderator emeritus
Jun 15, 2000
7,958
7
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:

Code:
- (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:

Code:
- (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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.