开发者

Fast enumeration?

开发者 https://www.devze.com 2023-04-12 14:07 出处:网络
I am currently developing a game and need really fast enumeration of arrays. I need to run the code 30 times per second and now want to ask what\'s the best way to accomplish the task.

I am currently developing a game and need really fast enumeration of arrays. I need to run the code 30 times per second and now want to ask what's the best way to accomplish the task. I want to enumerate an array 开发者_StackOverflowand modify it at the same time.

I know 2 at the moment:

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

and

int x=0;

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

What is the fastest way to do this? Do you know other ways? Thanks for your help!


In your particular case, the best way is probably to save off the indexes of objects you don't care about in an NSIndexSet and use them after the loop to remove all the objects at once.

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号