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

时间:2014-07-08 07:53:43

标签: ios iphone objective-c xcode sprite-kit

升级到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];
    }
}];

虽然我启用了异常断点和僵尸对象,但我没有进一步了解为什么会发生这种情况。错误是线程1 BreakPoint 1.3。 [level didSimulatePhysics] 非常感谢任何帮助。

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

1 个答案:

答案 0 :(得分:7)

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

通过延迟执行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并在枚举后删除该数组中的节点:

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];
}