有没有更有效的方法来清理我的CCNodes?

时间:2014-10-10 23:27:03

标签: objective-c cocos2d-iphone nsmutablearray

是否有更有效的方法来清理我的CCNode?我在计时器上调用了这个函数(以及其他类似的游戏对象)。

- (void)pulseBullets:(NSMutableArray *)bs targets:(NSArray *)targets {
    for (Bullet *b in bs) {
        for (QuantumPilot *p in targets) {
            if (p.active) {
                [p processBullet:b];
                if (!p.active) {
                    [self processKill:p];
                }
            }
        }
    }

    NSMutableArray *bulletsToErase = [NSMutableArray array];
    for (Bullet *b in bs) {
        [b pulse];
        if ([self bulletOutOfBounds:b]) {
            [bulletsToErase addObject:b];
        }
    }

    for (Bullet *b in bulletsToErase) {
        [b removeFromParentAndCleanup:YES];
    }

    [bs removeObjectsInArray:bulletsToErase];
}

1 个答案:

答案 0 :(得分:0)

好的,但我没有发表任何声明'在表现方面,你必须自己衡量。如果以相反的顺序迭代可变数组,则在迭代期间删除对象是安全的,因为删除操作不会使迭代器失效。因此,你可以摆脱子弹的altogther来擦除数组:

for (Bullet *b in [bs reverseObjectEnumerator]) {  // *** do not change iteration order ***
    for (QuantumPilot *p in targets) {
        if (p.active) {
            [p processBullet:b];
            if (!p.active) {
                [self processKill:p];
            }
        }
    }

    [b pulse];
    if ([self bulletOutOfBounds:b]) {
        [b removeFromParentAndCleanup:YES];
        [bs removeObject:b];
    }
}

这更简单,但会混淆迭代期间更改数组内容的固有风险。你打电话来询问它是否更清洁'。也许,费用可能是'反转迭代器的速度比你保存的更高,正如我所说,你必须测量它。

相关问题