Using enumerateObjectsAtIndexes or a for-loop to iterate through all indexes of an NSArray BEFORE a given index

StackOverflow https://stackoverflow.com/questions/15586508

Question

What's the most concise way to iterate through the indexes of an NSArray that occur before a given index? For example:

NSArray *myArray = @[ @"animal" , @"vegetable" , @"mineral" , @"piano" ];

[myArray enumerateObjectsAtIndexes:@"all before index 2" options:nil 
    usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
           // this block will be peformed on @"animal" and @"vegetable"
    }];

Also, this should not loop at all if the given index is 0.

What's the most concise, elegant way to do this? So far I've only cobbled together clumsy multi-line answers that use annoying NSRanges and index sets. Is there a better way I'm overlooking?

Was it helpful?

Solution 3

What about :

index = 2;
for (int i = 0; i < [myArray count] && i < index; ++i) {
   id currObj = [myArray objectAtIndex:i];
   // Do your stuff on currObj;
} 

OTHER TIPS

NSArray *myArray = @[ @"animal" , @"vegetable" , @"mineral" , @"piano" ];
NSUInteger stopIndex = 2;

[myArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if (idx == stopIndex) {
        *stop = YES; // stop enumeration
    } else {
        // Do something ...
        NSLog(@"%@", obj);
    }
}];
[myArray enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, idx)]     
                           options:0
                        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

}];

Personally I'd go with a block-based enumeration as shown by Martin R or yourfriendzak, the accepted answer by giorashc is probably the worst, as it doesn't provide a mutation guard.

I want to add a (correct) fast enumeration example

NSUInteger stopIndex = 2;
NSUInteger currentIndex = 0;
for (MyClass *obj in objArray) {
    if (currentIndex < stopIndex) {
        // do sth...
    } else {
        break;
    }
    ++currentIndex;      
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top