DenverCoder9
DenverCoder9

Reputation: 3705

Objective-C - fast enumeration on a subset of an array?

Is there a simple way to do fast enumeration on a range of objects in an array? Something like...

for (Object *object in myArray startingAtIndex:50) {
    //do stuff
}

...to avoid having to do something like this...

for (Object *object in myArray) {
    NSUInteger index = [myArray indexOfObject:object];
    if (index >= 50) {
        //do stuff
    }
}

Thanks.

Upvotes: 0

Views: 1081

Answers (2)

Regexident
Regexident

Reputation: 29562

These come to my mind:

for (Object *object in [myArray subArrayWithRange:NSMakeRange(50, ([myArray count] - 49))]) {
    //do stuff
}

Which creates a temporary array though, thus potentially being slower (benchmark it!) than manual enumeration like this:

NSUInteger arrayCount = [myArray count];
for (NSUInteger i = 50; i < arrayCount; i++) {
    Object *object = [myArray objectAtIndex];
    // do stuff
}

Upvotes: 5

bbum
bbum

Reputation: 162722

If myArray is immutable, then subArrayWithRange: probably does not copying of pointers, though retain probably still has to be sent to everything in the subarray.

Overall, it really doesn't matter. I've honestly never seen a case where fast enumeration vs. indexOfObject: was enough of a performance issue to warrant attention (there has always been something worse. :).

Another approach; use enumerateBlock: and simply return from indices out of ranger (and use the stop flag).

[myArray enumerateWithBlock: ^(id o, NSUInteger i, BOOL *f) {
   if (i < 10) return;
   if (i > 20) { *f = YES; return; }
   ... process objects in range ...
}];

(You could even use the options: variant to enumerate concurrently.)

Upvotes: 6

Related Questions