giojahn
giojahn

Reputation: 17

Use for-loop instead of repeating

Xcode noob here. Can anyone please guide me how to make list as below be done in for-loops? an if it possible? have it working with such lists but it takes too much time and can cause error due to repetition.

_monkey1.center = CGPointMake(_monkey1.center.x, _monkey1.center.y);
_monkey2.center = CGPointMake(_monkey2.center.x, _monkey2.center.y);
_monkey3.center = CGPointMake(_monkey3.center.x, _monkey3.center.y);
_monkey4.center = CGPointMake(_monkey4.center.x, _monkey4.center.y);
_monkey5.center = CGPointMake(_monkey5.center.x, _monkey5.center.y);
etc.

I have started with:

for (int k = 1; k < 20; k++){
// prep?
[[_monkeys objectAtIndex: k] setCenter: ....
}

Is there a possible way to do this? Any other suggestions would be appreciated.

monkeys are UIImageViews. Thanks.

Upvotes: 0

Views: 42

Answers (2)

Stackia
Stackia

Reputation: 2141

There is an another way to achieve this:

for (int k = 1; k < 20; k++) {
    YourMonkeyClass *monkey = [self valueForKey:[NSString stringWithFormat:@"monkey%ld", k]];
    monkey.center = CGPointMake(monkey.center.x, monkey.center.y);
}

for more details about valueForKey:, please refer to Key-Value Coding and Observing.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

NSArray *monkies = @[ _monkey1, _monkey2, _monkey3, _monkey4, _monkey5 ];
for (UIImageView *monkey in monkies) {
    monkey.center = CGPointMake(monkey.center.x, monkey.center.y);
}

(Note, I've assumed these objects are of type Monkey, which might be incorrect).

Upvotes: 1

Related Questions