gpt4 book ai didi

objective-c - 如何通过字符串获取实例名称

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:27:26 28 4
gpt4 key购买 nike

在Objective-C中如何通过一定的规则获取实例名?

例如:

类型 1:self.btn(0,1,2,3,4,5,6,7,8,9...) 在 for 循环中从 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 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 中,源代码如下。

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

最佳答案

在 objective-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];
}

关于objective-c - 如何通过字符串获取实例名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7075752/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com