You can subclass an NSArray with a class for ranges. Subclassing NSArray is pretty simple:
You can do more, but you do not need. There is no verification code in this sketch:
@interface RangeArray : NSArray - (id) initWithRangeFrom:(NSInteger)firstValue to:(NSInteger)lastValue; @end @implementation RangeArray { NSInteger start, count; } - (id) initWithRangeFrom:(NSInteger)firstValue to:(NSInteger)lastValue { // should check firstValue < lastValue and take appropriate action if not if((self = [super init])) { start = firstValue; count = lastValue - firstValue + 1; } return self; } // to subclass NSArray only need to override count & objectAtIndex: - (NSUInteger) count { return count; } - (id)objectAtIndex:(NSUInteger)index { if (index >= count) @throw [NSException exceptionWithName:NSRangeException reason:@"Index out of bounds" userInfo:nil]; else return [NSNumber numberWithInteger:(start + index)]; } @end
You can use it as follows:
NSArray *myRange = [[RangeArray alloc] initWithRangeFrom:1 to:10];
If you copy a RangeArray , it will become a normal array of NSNumber objects, but you can avoid it if you want using the NSCopying protocol NSCopying .
source share