开发者

How to construct and use a name of variable? [duplicate]

开发者 https://www.devze.com 2023-03-27 17:51 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: Objective-c create variables in a loop
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

Objective-c create variables in a loop

I have 10 UILabels, for the sake of simplicity let it be label0, label1, ..., label9. Now, I'm implementing a loop and I need to acces开发者_StackOverflow社区s appropriate label from appropriate loop cycle:

for (int i=0; i<10; i++){
  label"i".text = "value of label i";
}   

I need to construct variable name by binding loop cycle variable value to it. Any suggestions?


As best I know, there isn't a way to do this like you suggest. However, you can populate an NSMutableArray with UILabels and then call the object at index i to retrieve the ith label.

Create the labelArray (dynamically or statically), and then your for loop will be

for (int i=0; i<10; i++){
  [[labelArray objectAtIndex:i] setText:@"value of label i"];
}   


For every UILabel you can keep a tag. tag is an NSInteger.

So it could essentially be your index number itself...

You can access the labels by calling viewWithTag: on a parent UIView.


How about creating an array of those labels, and iterate with index?


I just ran across this today. This seems to be the original elegant solution you were looking for. It doesn't require any tags or special mutable arrays:

for (int i=0; i<10; i++){
    ((UILabel *)NSClassFromString([NSString stringWithFormat:@"label%i", i])).text = @"value of label i";
}


This is a fairly common use case. Typically this is solved my maintaining a map of strings to objects using an NSMutableDictionary:

NSMutableDictionary *labelMap = [[NSMutableDictionary alloc] initWithCapacity:10];
[labelMap setObject:[[[UILabel alloc] init] autorelease] forKey:@"label1"];
[labelMap setObject:[[[UILabel alloc] init] autorelease] forKey:@"label2"];
[labelMap setObject:[[[UILabel alloc] init] autorelease] forKey:@"label3"];
// etc

Then when you want to refer to an object by name:

for (int i=0; i<10; i++){ 
   NSString *labelKey = [NSString stringWithFormat:@"label%i", i];
   [labelMap objectForKey: labelKey].text = "value of label i";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消