如何通过String获取instanceName

时间:2011-08-16 08:54:19

标签: objective-c ios actionscript-3

在Objective-C中如何通过某些规则获取实例名称?

例如:

Type1:self.btn(0,1,2,3,4,5,6,7,8,9 ...)for for loop get number from i

for(int i = 0; i<10; i++){
//wrong code ( similar ActionScript3.0 code)
self."btn"+i = [UIButton buttonWithType:UIButonTypeRoundRect];
//i think code but, not available
self.[NSString stringWithFormat:@"btn%d", i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}

Type2:UIButton * btn(0,1,2,3,4,5,6,7,8,9 ...)for for loop get number from i

for(int i =0; i<10; i++){
//wrong code ( similar ActionScript3.0 code)
UIButton *"btn"+i = [UIButton buttonWithType:UIButtonTypeRoundRect];
//i think code but, not available
UIButton *[NSString stringWithFormat:@"btn%d", i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
}

因此,在ActionScript3.0中,Soruce如下所示。

for( var i=0; i<10; i++){
this["btn"+i] = new SimpeButton();
//btn0, btn1, btn2...btn10 get by for loop i object Simpebutton ten.
}

2 个答案:

答案 0 :(得分:1)

在目标c中,没有按钮的实例名称。有一个标记属性,您可以在其中存储整数值,以便您可以识别正确的按钮。 您可以在循环中创建按钮,设置正确的标记属性并存储在数组中:

NSMutableArray *buttonsArray = [[NSMutableArray alloc] init];
for( var i=0; i<10; i++) {
     UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundRect];
     button.tag = i;
     [buttonsArray addObject:button];
}

然后你可以用一种方式循环这个数组:

for (UIButton *aButton in buttonsArray) {
     // do something with aButton instance
}

或其他:

for (int i=0; i<[buttonsArray count]; i++) {
     // do something with [buttonsArray objectAtIndex:i];
}

答案 1 :(得分:0)

Objective-C中不存在这种精确的习语。相当于使用NSArray(或者,对于标识符没有按顺序编号的情况,使用NSDictionary)。