BuySellAds.com

My book Barcodes with iOS is nearing completion. Buy it now to get early access!
Our DNA is written in Objective-C
Jump

Key-Value-Coding

Simon asks:

I would like to loop through variables whose names end with numbers 0 to 5. What is the correct syntax for the i? I have tried variable[i], variable + i, without success

I know two methods to achieve this:

1. Put your objects into an array and then enumerate or for-loop over those

// e.g. in awakeFromNib
playerNameLabels = [[NSArray arrayWithObjects:player1NameLabel, player2NameLabel, player3NameLabel, nil] retain];
 
for (i=0;i<3;i++)
{
     UILabel *nameLabel = [playerNameLabels objectAtIndex:i];
     // do something the the nameLabel
}

2. Use the Key-Value-Coding approach.

// in this object's header the strings are defined, here we intialize them
string1 = @"string1";
string2 = @"string2";
string3 = @"string3";
 
int i;
 
for (i=1;i<3;i++)
{
     NSString *aName = [NSString stringWithFormat:@"string%d", i];
     NSString *oneString = [self valueForKey:aName];
     NSLog(@"string %d is '%@' and has length %d", i, oneString, [oneString length]);
}

The dangerous thing about the latter might be that you have construct precisely the right name for the value. Or else you will get an exception:

*** Terminating app due to uncaught exception ‘NSUnknownKeyException’, reason: ‘[<selectortestAppDelegate 0x524e80> valueForUndefinedKey:]: this class is not key value coding-compliant for the key string0.’

But actually the second approach is how Cocoa does most KVC internally.


Categories: Q&A

%d bloggers like this: