2012-10-16 83 views
0

可能重复:
Objective C Equivalent of PHP’s “Variable Variables”动态构造变量名

今天在我的班级之一,我了解到,你可以通过从ActionScript中的字符串构建的名称访问变量3.0,像这样:

var star1:symbol; 
var star2:symbol; 
var star3:symbol; 
var star4:symbol; 

for(i=1; i <= 4; i++) 
    [this "star" + i].method = something 

这得到star1,然后star2,然后star3,然后star4,并用它们做一些方法。

有没有办法在Objective-C中做这样的事情?

+0

难道你的意思是这个[“明星” + 1]。方法[ObjC相当于PHP的的“的 –

+0

可能重复变量变量“](http://stackoverflow.com/questions/2283374/objective-c-equivalent-of-phps-variable-variables),[基于int计数创建多个变量](http://stackoverflow.com/questions/2231783/create-multiple-variables-based-on-an-int-count /),[Syntax help:variable as object name](http://stackoverflow.com/questions/7940809/syntax-help-variable -as-object-name) –

回答

3

不太整洁,但是key-value coding确实是:

[self setValue:something forKey:[NSString stringWithFormat:@"star%u", i]] 

编辑:在反思目前还不清楚,作为一个非的Actionscript用户是否要访问的属性或调用方法。

你会使用NSSelectorFromString在运行时将方法的名称转换为选择器,然后在[self performSelector:...]的位置调用该方法,如果它是后者。

0

不,但你可以把变量放在一个数组中,并达到同样的效果。

1

是的。使用NSArray。然后,你可以做这样的事情:

NSArray *array = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil]; 
for (int i = 0; i < [array count]; i++) { 
    [[array objectAtIndex:i] doMethod]; 
} 

或者更简单:

NSArray *array = [NSArray arrayWithObjects:obj1, obj2, obj3, obj4, nil]; 
for (id obj in array) { 
    [obj doMethod]; 
} 
+2

甚至只是' @ [obj1,obj2,obj3,obj4]'在现代世界? – Tommy