快速列举?

use*_*246 3 iphone objective-c

我目前正在开发一款游戏,需要快速枚举数组.我需要每秒运行30次代码,现在想问一下完成任务的最佳方法是什么.我想枚举一个数组并同时修改它.

我现在知道2:

NSMutableArray*array;

int i=0;

int x=0;
 for (myclass*spr in [[array copy] autorelease]) {
    if ([spr isInBounds]) {
        //do something
    } else {
        [array removeObjectAtIndex:x];
        x--;
    }

    x++;
}
Run Code Online (Sandbox Code Playgroud)

int x=0;

while(x<[array count])
{
    if(![(myclass*)spr isInBounds]) {
        [array removeObjectAtIndex:x];
        x--;
    }
    x++;
}
Run Code Online (Sandbox Code Playgroud)

最快的方法是什么?你知道其他方法吗?谢谢你的帮助!

Lil*_*ard 6

在您的特定情况下,最好的方法可能是保存您不关心的对象的索引,NSIndexSet并在循环后使用它们一次删除所有对象.

NSMutableIndexSet *is = [NSMutableIndexSet indexSet];
[array enumerateObjectsUsingBlock:^(myclass *spr, NSUInteger idx, BOOL *stop) {
    if ([spr isInBounds]) {
        // do something
    } else {
        [is addIndex:idx];
    }
}];
[array removeObjectsAtIndexes:is];
Run Code Online (Sandbox Code Playgroud)