-1

I get this error once in a while when my program is running. Most of the time, the app works fine, but every now and then the app will crash and point to the second line in the for loop saying:

Terminating app due to uncaught exception 'NSGenericException', reason: '* Collection was mutated while being enumerated.'

for(int i = 1; i <= 121; i++) {
        NSLog(@"%i", i);
        [(UIButton *)[self.view viewWithTag:i] setImage:[UIImage imageNamed:@"hexagon"] forState:UIControlStateNormal];
}

What do I do to avoid my program from crashing??

user2905147
  • 21
  • 2
  • 4

1 Answers1

0

You are trying to change items in an array while you are looping through the array.

Try making a copy of the subviews to loop through so you can change the original.

NSArray *loopingArray = [self.view.subviews copy];

for (int i = 0; i < [loopingArray count]; i++){

    NSLog(@"%i", i);
    if ([self.view viewWithTag:i])
        [(UIButton *)[self.view viewWithTag:i] setImage:[UIImage imageNamed:@"hexagon"] forState:UIControlStateNormal];
}
digitalHound
  • 4,384
  • 27
  • 27