You're not missing anything. There isn't any really convenient way other than looping to do this. Of course any solution would be, at root, looping, but it would be nice if there were some more "filtering" or re-arranging abilities built in to NSArray
(/me coughs discreetly and looks at Python list comprehensions).
There's likely to be something useful in this vein in vikingosegundo's arraytools on GitHub, or similar collection-manipulation extensions by others. There's certainly no harm in writing your own category method to do this, though, like I said, there would have to be a loop somewhere in there.
Here's my suggestion, for whatever that's worth. Split the array by enumerating it:
NSMutableArray * keys = [NSMutableArray array];
NSMutableArray * values = [NSMutableArray array];
[array enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop)){
if( idx % 2 ){
[values addObject:obj];
else {
[keys addObject:obj];
}
}];
NSDictionary * d = [NSDictionary dictionaryWithObjects:values forKeys:keys];
Seems like there should be a better way to do this, such as with an NSIndexSet
and objectsAtIndexes:
, but there's no convenient way to create an index set with a non-contiguous bunch of indexes.
Something like this, e.g., would be nice:
@implementation NSIndexSet (WSSNonContiguous)
+ (id) WSS_indexSetWithOddIndexesInRange: (NSRange)range
{
NSMutableIndexSet * s = [NSMutableIndexSet indexSet];
// If the start of the range is even, start with the next number.
NSUInteger start = range.location % 2 ? range.location : range.location + 1;
NSUInteger upper_limit = range.location + range.length;
for( NSUInteger i = start; i < upper_limit; i += 2 ){
[s addIndex:i];
}
return s;
}
+ (id) WSS_indexSetWithEvenIndexesInRange: (NSRange)range
{
NSMutableIndexSet * s = [NSMutableIndexSet indexSet];
// If the start of the range is odd, start with the next number.
NSUInteger start = range.location % 2 ? range.location + 1 : range.location;
NSUInteger upper_limit = range.location + range.length;
for( NSUInteger i = start; i < upper_limit; i += 2 ){
[s addIndex:i];
}
return s;
}
@end
With a helper function:
NSRange rangeOfNumbers(NSUInteger start, NSUInteger end)
{
return (NSRange){start, end-start};
}
So that you can do this:
NSIndexSet * s = [NSIndexSet WSS_indexSetWithEvenIndexesInRange:rangeOfNumbers(0, 10)];
NSLog(@"%@", s);
// Prints: <NSMutableIndexSet: 0x7fccca4142a0>[number of indexes: 5 (in 5 ranges), indexes: (0 2 4 6 8)]