Senior Me
Senior Me

Reputation: 87

Is it possible to make a for loop changing property's

As the question asked I want to know if there is a possibility to change property's trough the int of a for loop.

example:

controller.h:

 @property (weak, nonatomic) IBOutlet UILabel *lblTeamName1;
 @property (weak, nonatomic) IBOutlet UILabel *lblTeamName2;
 @property (weak, nonatomic) IBOutlet UILabel *lblTeamName3;

controller.m

 @synthesize property lblTeamName1;
 @synthesize property lblTeamName2;
 @synthesize property lblTeamName3;     

 for(int i = 0;i <= 3;i++)
 {
  lblTeamName(i).text = @"something";
 }

What I am asking is a way for this to work, I have no idea if this will work or if this can't be done.

Upvotes: 0

Views: 53

Answers (2)

Fogmeister
Fogmeister

Reputation: 77641

You could do something like this...

for (int i=1; i<4; i++) {
    UILabel *label = [self objectForKey:[NSString stringWithFormat:@"lblTeamName%i", i]];
    label.text = @"blah";
}

This would rely on having a standard naming convention for your labels.

Oh, also, just a note. You no longer need to put @synthesize. If you're using Xcode 4.5 then they removed the need for using @synthesize. The compiler infers it if it is left out.

Upvotes: 0

Prine
Prine

Reputation: 12538

You could put the properties in an NSMutableArray and loop over that.

NSMutableArray *arr = [[NSMutableArray alloc] init];
[arr addObject:lblTeamName1];
[arr addObject:lblTeamName2];
[arr addObject:lblTeamName3];

for(UILabel *label in arr) {
  label.text = @"something";
}

Im not 100% sure, but I think there isn't anything like Java Reflection where you could manually get the defined properties and change the value. So you have to use an additional array to get that behaviour.

Upvotes: 2

Related Questions