Key-Value Coding ....a perspective please

Discussion in 'Mac Programming' started by mdeh, Mar 24, 2009.

  1. macrumors 6502

    Joined:
    Jan 3, 2009
    #1
    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.
     
  2. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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.
     
  3. thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #3
    Thanks kainjow
     
  4. macrumors 6502a

    GorillaPaws

    Joined:
    Oct 26, 2003
    Location:
    Richmond, VA
  5. thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #5
    good find...thank you....just read it....what I was looking for...thank you again, GorrillaPaws and to Kainjow
     

Share This Page