python怎么从数组中提取连续的数字_Objective-C数组中的连续数字,如Python中的range()...

本文介绍了如何在Objective-C中创建一个类`RangeArray`,该类模仿Python的`range()`功能,从指定的起始值到结束值生成连续的数字数组。通过子类化NSArray,实现了`count`和`objectAtIndex:`方法,从而能够创建并访问这个连续数字的数组对象。
摘要由CSDN通过智能技术生成

您可以使用范围类对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协议方法来避免它。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值