崩溃提示
崩溃提示:Terminating app due to uncaught exception ‘NSGenericException’, reason: ‘*** Collection <CALayerArray: 0x14df0bd0> was mutated while being enumerated.’
原因就是在变量数组的时候,改变了数组的内容(或增或减数组中的元素)。
解决办法
方法一
再定义一个一模一样的数组B,将原数组的内容复制给数组B,再遍历数组B
let arr2 = NSArray(array: arr)
for i in arr2.enumerated() {
}
方法二
创建一个串行队列,之后将对数组的操作全部放到该队列中
代码如下
_queue = dispatch_queue_create("com.app.serialQueue", DISPATCH_QUEUE_SERIAL);
dispatch_async(_queue, ^{
// 修改或者枚举遍历删除数组
});
方法三
用锁,互斥锁和递归锁。如果逻辑稍微有点复杂,为了防止死锁,还是用递归锁吧。
let lock = NSLock()// NSRecursiveLock()
self.lock.lock(); defer {
self.lock.unlock() }
参考:
- https://blog.csdn.net/feelinghappy/article/details/106664181
- https://stackoverflow.com/questions/27273211/array-was-mutated-while-being-enumerated-swift
- https://juejin.cn/post/7007983045345034247