美文网首页
项目中的问题

项目中的问题

作者: 写下岁月的痕迹 | 来源:发表于2019-06-12 17:10 被阅读0次

控制台的Log:Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <__NSArrayM: 0x2811ebed0> was mutated while being enumerated.’

一、原因:

1、某个数组在遍历的时候,同时又在修改数组中的内容,才导致的崩溃。
2、for in 方法的原理是根据 enumerator对象内部的计数器,调用nextObject方法来实现返回下一个数组元素的,知道元素全部返回就会返回nil,这就代表着整个enumerator对象就遍历完成了。需要注意的是以这种原理来遍历enumrator对象的话, 无论对这个对象做什么操作, 对象的计数器都不会被重置!

二、解决方案:

方案一:新创建一个临时的数组,将原始数组的数据拷贝到新的临时数组;代码如下:

NSMutableArray  *dataArray = xxx; 
NSArray  *tmpArr = [NSArray arrayWithArray: dataArray];  
for (NSDictionary *dic in tmpArr) {        
    if (condition){            
         [dataArray removeObject:dic];
    }      
 }

方案二:使用带有block的数组NSArray/NSMutableArray的系统API,找到符合条件的时候,暂停遍历,对数组的内容进行修改。代码如下:

NSMutableArray  *dataArray = xxx; 
dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (condition) {
        *stop = YES;
        if (*stop == YES) {
            [dataArray replaceObjectAtIndex:idx withObject:@"ooo"];
        }
    }
}

参考的文章:
https://www.jianshu.com/p/1a3065a07cbc
https://www.jianshu.com/p/c2678ff90e46

相关文章

网友评论

      本文标题:项目中的问题

      本文链接:https://www.haomeiwen.com/subject/cxwlfctx.html