2013-02-24 91 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