遍历数组修改数据导致的错误

来源:互联网 发布:淘宝登录不了怎么办 编辑:程序博客网 时间:2024/04/27 06:44

错误提示:

Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0xb550c30> was mutated while being enumerated.’

原因:由于遍历数组时候 修改了数组中的数据  导致错误。

解决办法:

定义一个数组B,并把要遍历的数组A的值赋给他 。

然后遍历数组B 要修改数据的A就可以修改数据了。

NSArray *arr = content[@"workface"];

            for (NSDictionary *dictin arr) {

                if ([dict[@"workfaceid"]isEqual:_faceInfo[@"workfaceid"]]) {

                    // 先移除后添加

                    [content[@"workface"]removeObject:dict];

                    [content[@"workface"]addObject:_faceInfo];

                }

            }


另一种快捷 的方法是

[self.viceMoreselsenumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx,BOOL * _Nonnull stop) {

                    if ([objisEqualToString:[@(sender.tag-10001)stringValue]]) {

                        *stop = YES;

                        if (*stop==YES) {

                            [self.viceMoreselsremoveObjectAtIndex:idx];

                        }

                    }

                }];

这种方法  遍历速度更快 。
0 0
原创粉丝点击