BigT
BigT

Reputation: 1433

Mutated array while being enumerated

The error I am getting is

Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <CALayerArray: 0x7c85080> was mutated while being enumerated.'

What I understand from NSGenericException is that I am removing something from my array while it is enumerating. Still knowing that and looking around I can not seem to resolve my issue. Here is the code below.

-(void)tableView(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
     //Checks if message has been read. If message has not it updates the unreadMessages array
     if ([unreadMessage containsObject:[NSString stringWithFormat:@"m%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]] == TRUE && [[[storage_array objectAtIndex:indexPath.row] objectForKey:@"itemtype"] isEqualToString:@"message"]  == TRUE){

     //Unread
     [unreadMessage removeObject:[NSString stringWithFormat:@"m%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]];
     [unreadMessage writeToFile:[self saveUnreadMessages] atomically:YES];
     //Read
     [readMessage addObject:[NSString stringWithFormat:@"m%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]];
     [readMessage writeToFile:[self saveReadMessages] atomically:YES];
     [tableView reloadData];
 }
 else if ([unreadNewsletter containsObject:[NSString stringWithFormat:@"n%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]] == TRUE && [[[storage_array objectAtIndex:indexPath.row] objectForKey:@"itemtype"] isEqualToString:@"newsletter"]  == TRUE){

     //Unread
     [unreadNewsletter removeObject:[NSString stringWithFormat:@"n%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]];
     [unreadNewsletter writeToFile:[self saveUnreadNewsletters] atomically:YES];
     //Read
     [readNewsletter addObject:[NSString stringWithFormat:@"n%@",[[storage_array objectAtIndex:indexPath.row] objectForKey:@"id"]]];
     [readNewsletter writeToFile:[self saveReadNewsletters] atomically:YES];
     [tableView reloadData];
 }
}

Upvotes: 0

Views: 2959

Answers (2)

Jeff Hellman
Jeff Hellman

Reputation: 2117

Alternatively, you could build up a new NSMutableArray of the objects needing to be removed while iterating through your original mutable array and then, after the loop completes, call

[originalMutableArray removeObjects:newArrayContainingObjectsNeedingToBeRemoved];

Upvotes: 0

You shouldn't modify the array you are iterating over. If you intent to do so, you should iterate over a copy of it:

for (id item in [array copy])
{
    …
}

(with ARC. [[array copy] autorelease] without ARC.)

If needed, you can check if the item is still in the mutable array before doing anything with it.

Upvotes: 5

Related Questions