我有一些變數,如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