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?

有帮助吗?

解决方案

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;

其他提示

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top