Andrew
Andrew

Reputation: 16051

Refer to the name of something without actually writing it

I'm not sure how to put this best into a title, but this is what i want. Say i'm creating a number of UIlabels programmatically, and i want them to have the names label1, label2, label3 ect.

How do i name a new label the next one. And say i know i want to refer to label3 at this point, but i might want to refer to another number at another point, how would i write that in the code?

so instead of label5.text = ..., what could i put? Because it won't always be label5.

Upvotes: 0

Views: 150

Answers (3)

Luke
Luke

Reputation: 2572

Don't confuse yourself! It's tempting to think:

for (int i=1; i<5; i++){
    UILabel ([NSString stringWithFormat@"label%d", i]) = [[UILabel alloc] init];}

Or something like that would work. The names we use are for our convenience, the compiler uses the pointer to the object instead of the label.

What could work is an array or set of the pointers:

NSMutableArray *labels = [[NSMutableArray alloc] init];
for (int i=1; i<5; i++){
    [labels addObject:[UILabel alloc] initWith...];
}
...
[[labels objectAtIndex:index] setText:newText];

Upvotes: 5

DavidPhillipOster
DavidPhillipOster

Reputation: 4495

This is a job for an NSMutableArray of UILabels. use addObject to append to the array. Use objectAtIndex: to refer to the i'Th.

Upvotes: 0

Cosmin
Cosmin

Reputation: 2385

Label myLabel = label5;
myLabel.text = ...
myLabel = label7;
myLabel.text = ...

Upvotes: 0

Related Questions