2013-02-24 60 views
-4

我有一些变数,如vh1vh2vh3等 是否有可能在for循环计数与我变量?客观C变数

我的意思是这样for(int i = 1; blablabla) { [[vh + i] setBackGroundColor blablabla];}

问候

编辑:VH1等都是UILabels!

+0

答案是否定的 – Ares 2013-02-24 07:43:58

回答

3

虽然这种通过introspection是可能的,如果你有这样的变量,你最好把它们放在一个NSArray,并使用索引访问它们。

+0

但变量是UILabels,所以是有可能把它们放入数组? – Phil 2013-02-24 07:58:05

+0

是的,在'NSArray'中。 – MByD 2013-02-24 07:58:32

+0

你有我的例子吗?直到现在我做'IBOutlet UILabel * vh1;'(与其他人一样)我怎样才能把它放入数组? – Phil 2013-02-24 08:10:45

0

您可以访问每个值下面的代码。

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]; 
} 
+0

感谢您的所有答案。 Iam使用'IBOutlet UILabel * vh1;'创建它们,然后尝试用数组的方式访问它们,但它不起作用。 '''之前预期的blablabla'='token':/ – Phil 2013-02-24 08:27:01

+0

你是否在viewController上编写了这段代码?你想展示UILabels? – akiniwa 2013-02-24 08:35:14

+0

是的,它将是一个iPhone应用程序,我在viewController – Phil 2013-02-24 08:41:13

0

如果从XIB加载UILabels,您可以使用IBOutletCollection

财产申报:

@property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *labels; 

现在你可以链接多个标签在XIB这个属性。然后在-viewDidLoad(装载XIB后),您的数组填充,您只需使用简单的for-in

for (UILabel *label in self.labels) { 
    label.backgroundColor = ... 
} 
+0

无效:/''strong'之前需要属性属性'' – Phil 2013-02-24 08:35:26

+0

我将该行复制/粘贴到代码并编译并运行。 – Tricertops 2013-02-24 09:11:03

1

至于其他的应答者已经注意到,随着新的数组语法,你可以很轻松地构建与您的所有对象的数组。在其中,但即使您随后更改原始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

+0

''obj'undeclared':/ – Phil 2013-02-24 10:01:58

+0

@ user1794338这只是一种指向具有变量的对象的方式,可以是自我,编辑答案。 – Monolo 2013-02-24 11:14:53