3

Possible Duplicate:
create multiple variables based on an int count
Objective C Equivalent of PHP's “Variable Variables”

I'd like to use some dynamic variable names in a for loop and am stumped as to how to actually reference the variables.

I have a series of UILabels title poll0 - poll8. Using a for loop, I set their text value to another value referenced from that corresponding number in an array. For example:

for (int i = 0; i < [pollData count]; i++) {
    label(i value).text = [NSString stringWithFormat:@"%@", [[pollData objectAtIndex:i] toString]]; //sorry for the java-esque method names, just create what I'm used to
}

How do I use that i value?

Community
  • 1
  • 1
Peter Kazazes
  • 3,600
  • 7
  • 31
  • 60

2 Answers2

5

You can't do exactly what you're asking. The best approach would be to put your labels in an array and loop through the array:

NSArray *labels = [NSArray arrayWithObjects:poll0, poll1, poll2, ..., nil];
for (UILabel *label in labels) {
    label.text = [[pollData objectAtIndex:i] toString];
}

You might also want to take a look at IBOutletCollections as they'll allow you to group the labels into an array without writing the array initialization code above. Instead, you put this in your .h file, then hook the labels outlet up to all your labels in Interface Builder:

@property (nonatomic, retain) IBOutletCollection(UILabel) NSArray *labels;
Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • Beat me to it :) and I'm always wary of using fast enumeration like this, but the documentation says that it should proceed in proper order. – rosslebeau Mar 30 '12 at 02:35
  • Yes, you can be sure that fast enumeration really does work in order for arrays. I use it all the time! – Andrew Madsen Mar 30 '12 at 02:36
  • How have I been programming via IB for so long and never known about IBOutletCollections? My god, I should be giving you 50% of the money made in the time I'll be saving from this point forward. Thank you! – Peter Kazazes Mar 30 '12 at 02:44
  • In your defense, it was new in iOS4, but it certainly is a nice feature. Glad I could help. – Andrew Madsen Mar 30 '12 at 03:33
0

You can create an array with UILabel** instead of using NSArray. By this way you can use array elements without a casting to UILabel

Gargo
  • 704
  • 6
  • 16