尝试使用快速枚举从父级删除节点时出错

升级到iOS 8 b3和Xcode 6 b3后,在didSimulatePhysics方法中出现错误:

[self enumerateChildNodesWithName:@"name" usingBlock:^(SKNode *node, BOOL *stop) { if (node.position.y < 0 || node.position.x>320 || node.position.x<0) { [node removeFromParent]; } }]; 

虽然我有exception断点启用和僵尸对象,我没有进一步的信息,为什么发生这种情况。 错误是线程1 BreakPoint 1.3。 [水平didSimulatePhysics]任何帮助,非常感谢。

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

行为可能会在iOS版本之间改变。 它可能实际上已经崩溃了,甚至在Xcode 5中很less发生,你只是没有看到它。

这个问题很容易通过延迟removeFromParent方法的执行来绕过。 这应该做的伎俩,因为行动在游戏循环中的特定点而不是瞬间评估:

 [self enumerateChildNodesWithName:@"name" usingBlock:^(SKNode *node, BOOL *stop) { if (node.position.y < 0 || node.position.x>320 || node.position.x<0) { [node runAction:[SKAction removeFromParent]]; } }]; 

如果这不起作用,则使用“旧技巧”:向NSMutableArray填充要删除的项目,并在枚举之后删除该arrays中的节点:

 NSMutableArray* toBeDeleted = [NSMutableArray array]; [self enumerateChildNodesWithName:@"name" usingBlock:^(SKNode *node, BOOL *stop) { if (node.position.y < 0 || node.position.x>320 || node.position.x<0) { [toBeDeleted addObject:node]; } }]; for (CCNode* node in toBeDeleted) { [node removeFromParent]; }