multithreading - swift - 使用 enumerateChildNodesWithName 的多线程错误

标签 multithreading swift sprite-kit

我喜欢在我的 spritekit 游戏中使用多线程。 我使用 enumerateChildNodesWithName 然后我检查这个对象是否与玩家发生碰撞。我想在另一个线程上执行这部分。

这是我的代码:let updateQueue: dispatch_queue_t = dispatch_queue_create("my.game", DISPATCH_QUEUE_CONCURRENT)

dispatch_async(updateQueue, { () -> Void in
            self.enumerateChildNodesWithName("lockGreen", usingBlock: { (lockGreen, stop) -> Void in
                if CGRectIntersectsRect(player.frame, lockGreen.frame) && keyGreenCollected {
                    lockGreen.removeFromParent()
                }
            })
        })

但是我得到了这个错误。我该如何解决这个问题?

*** Terminating app due to uncaught exception 'NSGenericException',   reason: '*** Collection <__NSArrayM: 0x1702407b0> was mutated while being enumerated.'
*** First throw call stack:
(0x1827c822c 0x1944940e4 0x1827c7be0 0x1870ca4bc 0x1870c9c08 0x1870c95a0 0x1000ea904 0x1000e722c 0x100954fd4 0x100954f94 0x10095e8f0 0x100954f94 0x100962b54 0x100964248 0x194cf121c 0x194cf0ee0)`
libc++abi.dylib: terminating with uncaught exception of type NSException`

谢谢

最佳答案

发生此错误是因为您在循环遍历其元素时正在修改集合。它与多线程无关。

使用 removeFromParent 从其父节点中删除一个节点,将从父节点树中删除该节点。它还从其父节点的 children 数组中删除该节点。发生此错误是因为您正在修改 self.children 数组(使用 removeFromParent),同时使用 enumerateChildNodesWithName 遍历数组的元素。

关于multithreading - swift - 使用 enumerateChildNodesWithName 的多线程错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32464988/

相关文章:

swift - TVOS 10 SpriteKit Focus Navigation 默认聚焦项

sprite-kit - Xcode 6 Sprite 套件 - 如何实现 "initwithsize"

ios - 如何调用 touchesBegan 函数?

c# - 如何正确处置 Form,而不会有从已处置对象上的另一个线程调用 Invoke 的风险?

c - 在线程库中使用 getcontext() 时出现段错误

c - 如何在 C 中跨线程进行动态数据传输和内存管理?

c++ - CPP : How to create a thread with method that requires pointer?

带有 args 的 Swift 函数...传递给带有 args 的另一个函数

ios - 以字符串形式访问自定义对象属性 (NSMutableArray)

swift - 绕过 WatchKit 中的 playHaptic 预定义案例