objective-cnsarrayiterationnsrangensindexset

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


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?


Solution

  • What about :

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