user610246
user610246

Reputation: 762

Fast enumeration?

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 and 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!

Upvotes: 3

Views: 532

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185653

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

Upvotes: 6

Related Questions