代码改变世界

遍历数组的同时修改数组

2015-09-08 11:31  唐不坏  阅读(1254)  评论(0)    收藏  举报

在for循环forin遍历数组的同时,如果修改数组会报错:Collection <__NSArrayM: ???????> was mutated while being enumerated。
最好的解决方法是使用枚举

e.g.

NSMutableArray *tempArray = [[NSMutableArray alloc]initWithObjects:@"12",@"23",@"34",@"45",@"56", nil];
 
[tempArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
 
if ([obj isEqualToString:@"34"]) {
 
*stop = YES;
 
if (*stop == YES) {
 
[tempArray replaceObjectAtIndex:idx withObject:@"3333333"];
 
}
 
}
 
if (*stop) {
 
NSLog(@"array is %@",tempArray);
 
}
 
}];