IOS dynamic variable names

Possible duplicate:
create multiple variables based on int
Objective C PHP variable variable equivalent

I would like to use some dynamic variable names in a for loop and do not understand how to actually reference the variables.

I have a series of UILabels title poll0

- poll8

. Using a for loop, I set the value text

to another value that is referenced by this number in the 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 to use the value i

?

+3


source to share


2 answers


You cannot do what you ask. 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 can also take a look at IBOutletCollections as they will allow you to group labels into an array without writing the above array initialization code. Instead, you put this in your .h file and then include shortcuts to all of your shortcuts in Interface Builder:

@property (nonatomic, retain) IBOutletCollection(UILabel) NSArray *labels;

      

+5


source


You can create an array with UILabel ** instead of using NSArray. This way you can use non-cast array elements in UILabel



0


source







All Articles