我得到的错误是
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];
}
}
答案 0 :(得分:5)
您不应该修改正在迭代的数组。如果您打算这样做,您应该迭代它的副本:
for (id item in [array copy])
{
…
}
(使用ARC。[[array copy] autorelease]
没有ARC。)
如果需要,您可以在执行任何操作之前检查该项目是否仍在可变数组中。
答案 1 :(得分:0)
或者,您可以在迭代原始可变数组时构建需要删除的对象的新NSMutableArray,然后在循环完成后调用
[originalMutableArray removeObjects:newArrayContainingObjectsNeedingToBeRemoved];