我有一些变数,如vh1
vh2
vh3
等 是否有可能在for循环计数与我变量?客观C变数
我的意思是这样for(int i = 1; blablabla) { [[vh + i] setBackGroundColor blablabla];}
问候
编辑:VH1等都是UILabels!
我有一些变数,如vh1
vh2
vh3
等 是否有可能在for循环计数与我变量?客观C变数
我的意思是这样for(int i = 1; blablabla) { [[vh + i] setBackGroundColor blablabla];}
问候
编辑:VH1等都是UILabels!
虽然这种通过introspection是可能的,如果你有这样的变量,你最好把它们放在一个NSArray,并使用索引访问它们。
您可以访问每个值下面的代码。
UILabel *label1;
UILabel *label2;
UILabel *label3;
NSArray *array = @[label1, label2, label3];
for (int i = 0; i<3; i++) {
[array objectAtIndex:i];
}
向NSArray添加值可用于初始化它。 如果您想稍后添加值,则可以使用NSMutableArray。
我修改了我的代码。
UILabel *label1 = [[UILabel alloc] init];
UILabel *label2 = [[UILabel alloc] init];
UILabel *label3 = [[UILabel alloc] init];
NSArray *array = @[label1, label2, label3];
for (int i = 0; i<3; i++) {
UILabel *label = [array objectAtIndex:i];
label.frame = CGRectMake(0, i*100, 150, 80);
label.text = [NSString stringWithFormat:@"label%d", i];
[self.view addSubview:label];
}
如果从XIB加载UILabels
,您可以使用IBOutletCollection
。
财产申报:
@property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *labels;
现在你可以链接多个标签在XIB这个属性。然后在-viewDidLoad
(装载XIB后),您的数组填充,您只需使用简单的for-in
:
for (UILabel *label in self.labels) {
label.backgroundColor = ...
}
无效:/''strong'之前需要属性属性'' – Phil 2013-02-24 08:35:26
我将该行复制/粘贴到代码并编译并运行。 – Tricertops 2013-02-24 09:11:03
至于其他的应答者已经注意到,随着新的数组语法,你可以很轻松地构建与您的所有对象的数组。在其中,但即使您随后更改原始ivars的值,它也会保留旧值。这可能是也可能不是你所追求的。
如果你是拼命保持你的变量作为单个对象(而不是数组),那么你可以使用键 - 值编码以编程方式访问它们。键值编码也被称为KVC。
,做它是valueForKey:
,并且可以在self
和其它目的使用这两种方法。
MyClass *obj = ... // A reference to the object whose variables you want to access
for (int i = 1; i <= 3; i++) {
NSString *varName = [NSString stringWithFormat: @"var%d", i];
// Instead of id, use the real type of your variables
id value = [obj valueForKey: varName];
// Do what you need with your value
}
还有更多关于KVC的docs。
为了完整起见,此直接访问工作的原因是因为标准KVC兼容对象继承了名为accessInstanceVariablesDirectly
的类方法。如果您不要支持这种直接访问,那么你应该重写accessInstanceVariablesDirectly
所以它返回NO
。
答案是否定的 – Ares 2013-02-24 07:43:58