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?
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) {
}];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With