I know how to do it in Ruby, converting a range of numbers to an array. But how is it possible in Objective-C?
Ruby:
(1..100).to_a
I know how to do it in Ruby, converting a range of numbers to an array. But how is it possible in Objective-C?
Ruby:
(1..100).to_a
You've got to do it manually:
// Assuming you've got a "NSRange range;"
NSMutableArray *array = [NSMutableArray array];
for (NSUInteger i = range.location; i < range.location + range.length; i++) {
[array addObject:[NSNumber numberWithUnsignedInteger:i]];
}
You might want to try NSIndexSet instead.
NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1, 100)];
Just to throw a whacky solution in from the left:
The idea is to have the Key-Value Coding machinery create the array for you, through indexed properties.
Interface:
@interface RangeArrayFactory : NSObject {
NSRange range;
}
@end
Implementation:
- (id)initWithRange: (NSRange)aRange
{
self = [super init];
if (self) {
range = aRange;
}
return self;
}
// KVC for a synthetic array
- (NSUInteger) countOfArray
{
return range.length;
}
- (id) objectInArrayAtIndex: (NSUInteger) index
{
return [NSNumber numberWithInteger:range.location + index];
}
Use:
NSRange range = NSMakeRange(5, 10);
NSArray *syntheticArray = [[[RangeArrayFactory alloc] initWithRange: range] valueForKey: @"array"];
This solution is mostly for fun, but it might make sense for large ranges, where a real array filled with consecutive numbers will take up more memory than is actually needed.
As noted by Rob Napier in the comments, you could also subclass NSArray, which just requires you to implement count and objectForIndex:, using the same code as countOfArray and objectInArrayAtIndex above.
You'll need to write a simple loop. There isn't any "range of numbers" operator in Objective-C.