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.
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];
Label myLabel = label5;
myLabel.text = ...
myLabel = label7;
myLabel.text = ...
This is a job for an NSMutableArray of UILabels. use addObject to append to the array. Use objectAtIndex: to refer to the i'Th.
精彩评论