I have some variables like vh1
vh2
vh3
etc.
Is it possible in a for-loop to count with the i variable?
I mean something like for(int i = 1; blablabla) { [[vh + i] setBackGroundColor blablabla];}
Regards
Edit: vh1 etc. are UILabels!!!
I have some variables like vh1
vh2
vh3
etc.
Is it possible in a for-loop to count with the i variable?
I mean something like for(int i = 1; blablabla) { [[vh + i] setBackGroundColor blablabla];}
Regards
Edit: vh1 etc. are UILabels!!!
While this is possible through introspection, if you have such variables you better put them in an NSArray, and access them with an index.
As other answerers have noted, with the new array syntax you can quite easily construct an array with all your objects in it, but it will keep the old values even if you subsequently change the values of the original ivars. That may or may not be what you are after.
If you are hell-bent on keeping your variables as single objects (as opposed to arrays,) then you can use key-value coding to access them programmatically. Key-value coding is also known as KVC.
The method that does it is valueForKey:
and can be used both on self
and other objects.
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
}
There is more about KVC in the docs.
In the interest of completeness, the reason this direct access works, is because a standard KVC compliant object inherits a class method called accessInstanceVariablesDirectly
. If you don't want to support this direct access, then you should override accessInstanceVariablesDirectly
so it returns NO
.
You can access each values the following code.
UILabel *label1;
UILabel *label2;
UILabel *label3;
NSArray *array = @[label1, label2, label3];
for (int i = 0; i<3; i++) {
[array objectAtIndex:i];
}
Adding values to NSArray is available for initializing it. If you want to add values later, you can use NSMutableArray.
I modified my code.
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];
}
If you are loading the UILabels
from XIB, you can use IBOutletCollection
.
Declare property:
@property (nonatomic, strong) IBOutletCollection(UILabel) NSArray *labels;
Now you can link multiple labels in XIB to this property. Then in -viewDidLoad
(after loading the XIB), your array is populated and you just use simple for-in
:
for (UILabel *label in self.labels) {
label.backgroundColor = ...
}