Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
zakdances Avatar asked Dec 31 '25 13:12

zakdances


2 Answers

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);
    }
}];
like image 157
Martin R Avatar answered Jan 02 '26 04:01

Martin R


[myArray enumerateObjectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, idx)]     
                           options:0
                        usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {

}];
like image 31
zakdances Avatar answered Jan 02 '26 04:01

zakdances