0

我得到的错误是

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

我从中了解到的NSGenericException是,我在枚举时从数组中删除了一些东西。仍然知道这一点并环顾四周,我似乎无法解决我的问题。这是下面的代码。

-(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];
 }
}
4

2 回答 2

5

您不应该修改您正在迭代的数组。如果您打算这样做,您应该遍历它的副本:

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

(有 ARC。[[array copy] autorelease]没有 ARC。)

如果需要,您可以在对其进行任何操作之前检查该项目是否仍在可变数组中。

于 2012-06-27T16:46:47.620 回答
0

或者,您可以在迭代原始可变数组时构建需要删除的对象的新 NSMutableArray ,然后在循环完成后调用

[originalMutableArray removeObjects:newArrayContainingObjectsNeedingToBeRemoved];
于 2012-06-27T16:58:50.803 回答