您可以使用范围类对NSArray进行子类化。子类化NSArray非常简单:
你需要一个合适的初始化方法,它调用[super init];和
您需要覆盖count和objectAtIndex:
你可以做更多,但你不需要。这是一个缺少一些检查代码的草图:
@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您可以按如下方式使用:
NSArray *myRange = [[RangeArray alloc] initWithRangeFrom:1 to:10];如果你copy一个RangeArray它将成为NSNumber对象的正常数组,但是你可以通过实现NSCopying协议方法来避免它。