nsarray was mutated while being enumerated

来源:互联网 发布:单片机51串口通信程序 编辑:程序博客网 时间:2024/06/08 07:09

  在遍历数组过程中,找到要删除的元素并删除的时候会报错

尤其发生在使用array的block方法

/*Collection  was mutated while being enumerated        *///                        [commentList enumerateObjectsWithOptions:NSEnumerationConcurrent usingBlock:^(id obj, NSUInteger idx, BOOL *stop){//                            if ([[(NSDictionary *)obj objectForKey:@"id"] isEqualToString:dic[@"id"]]) {//                                [arr removeObjectIdenticalTo:dic];//                            }//                        }];
正确的做法是将该数组拷贝一份,对新数组进行遍历,然后对原始数组中得元素进行删除操作

Using a for loop instead of enumerating is ok. But once you start deleting array elements, be careful if you're using threads. It's not enough to just decrement the counter as you may be deleting the wrong things. One of the correct ways is to create a copy of the array, iterate the copy and delete from the original.

见http://stackoverflow.com/questions/10157381/nsarray-was-mutated-while-being-enumerated

    NSMutableArray *origins =[[NSMutableArray alloc]initWithArray:(NSArray *)[result objectForKey:@"data"]];                    NSMutableArray *arr = [[NSMutableArray alloc]initWithArray:origins copyItems:YES];                    if (arr==nil||[arr count]==0) {                        return ;                    }                    for (NSDictionary *dic in arr) {                        for (NSDictionary *dict in commentList) {                            if ([dic[@"id"] isEqualToString:dict[@"id"]]) {                                [origins removeObject:dic];                            }                        }


0 0
原创粉丝点击