I have a UIView *buttonView filled with buttons. I need to update my list and re-populate my buttonView. I implemented:
if ([[self.buttonView.subviews objectAtIndex:i] isKindOfClass:[UIButon class]]
[[self.buttonView.subviews objectAtIndex:i] removeFromSuperview];
but it failed, it would not remove all the buttons (with my test with 8 buttons, it removed every other button :-?)
I then tried:
for(UIView *subview in self.buttonView.subviews)
{
if([subview isKindOfClass:[UIButton class]])
[subview removeFromSuperview];
}
and it worked perfectly.
Shouldn’t both loops accomplish the same thing?
I’m guessing there is something I don’t know about fast enumeration that would explain this?
I don’t believe you’re allowed to modify the collection you’re enumerating, so be careful with that. It seems like it handles the changes just fine though, and it will get through every item (unlike the for loop).
In the first case, it wouldn’t work because once you remove index 0, something else becomes index 0, but you’ve moved on to index 1. You could fix it by decrementing your loop variable in the event that the remove succeeds, so that the loop increments it to its previous value:
What happens with your for loop:
1,2,3,4,5,6,7,8and remove first item (1)2,3,4,5,6,7,8and remove second item (3)2,4,5,6,7,8and remove third item (5)2,4,6,7,8and remove fourth item (7).2,4,6,8and you’re on index 5, which is greater than length, so you’re done.