Possible Duplicate:
Objective-C NSMutableArray mutated while being enumerated?
I use this code to remove an object at index:
-(IBAction)deleteMessage:(id)sender{
UIButton *button = (UIButton*) sender;
for (UIImageView *imageView in imageArray)
{
if ([imageView isKindOfClass:[UIImageView class]] && imageView.tag == button.tag)
{
if (imageView.frame.size.height == 60) {
x = 60;
}
if (imageView.frame.size.height == 200) {
x = 200;
}
for (UITextView *text in messagetext)
{
for (UITextView *name in messagename)
{
if ([text isKindOfClass:[UITextView class]] && text.tag == button.tag && text.tag== name.tag)
{
[imageView removeFromSuperview];
[messagename removeObjectAtIndex:button.tag - 1];
[messagetext removeObjectAtIndex:button.tag - 1];
}
}
}
The error is:
*** Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x704bdb0> was mutated while being enumerated.'
I noticed though that if I delete first the last object in the array, and go in order from last to firs, it works. But if I try removing an object at an index that is not the last, the app crashes and gives the error: (1,2,3,4..I delete object2… crash…if I delete object 4 no crash)
One way to do this is to make an array with the indexes you intend to remove, the you do your loop, add the indexes and remove the objects afterwards. Something like this:
Now if you want different indexes for both arrays just make another
NSMutableIndexSetand add the second set of indexes to it. Also don’t forget to releaseindexesif you don’t use ARC.