If you want to create a large array quickly, or one which is a range, then you can create an array which doesn't actually store all the values but computes them on the fly as needed.
To subclass NSArray
you only need to implement two methods, count
and objectAtIndex:
, for your subclass to be a complete array.
Here is an implementation, so simple there are no comments ;-)
@interface RangeArray : NSArray
- (instancetype) initWithStart:(NSInteger)start end:(NSInteger)end step:(NSInteger)step;
@end
@implementation RangeArray
{
NSInteger start, end, step;
NSInteger count;
}
- (instancetype) initWithStart:(NSInteger)_start end:(NSInteger)_end step:(NSInteger)_step
{
self = [super init];
if (self)
{
start = _start;
end = _end;
step = _step;
count = (end >= start && step > 0) || (end < start && step < 0) ? 1 + (end - start) / step : 0;
}
return self;
}
- (NSUInteger) count { return count; }
- (id) objectAtIndex:(NSUInteger)index { return @(start + step * index); }
@end
And you can generate your required range using:
RangeArray *range = [RangeArray.alloc initWithStart:0 end:10000 step:500];
HTH