Python は、次のように連続した数字でリストを作成できます。
numbers=range(1,10); // >> [1,2,3,4,5,6,7,8,9]
Objective-cでこれを実装する方法は?
Python は、次のように連続した数字でリストを作成できます。
numbers=range(1,10); // >> [1,2,3,4,5,6,7,8,9]
Objective-cでこれを実装する方法は?
あなたのステートメント「Just need an array with continuous numbers,I do not want it to init with a loop」を読んで、私に尋ねさせてください: あなたにとってもっと重要なことは何ですかarray
:自然)数。ご覧ください。あなたが望むものに近づくかもしれません。で初期化しますNSIndexSet
[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1,9)];
このセットの繰り返しは、配列の繰り返しと同じくらい簡単で、NSNumbers は必要ありません。
Objective-C (または実際には Foundation) には、このための特別な機能はありません。あなたが使用することができます:
NSMutableArray *array = [NSMutableArray array];
for(int i=1; i<10; i++) {
[array addObject:@(i)]; // @() is the modern objective-c syntax, to box the value into an NSNumber.
}
// If you need an immutable array, add NSArray *immutableArray = [array copy];
もっと頻繁に使用したい場合は、オプションでカテゴリに入れることができます。
使用できますNSRange
。
NSRange numbers = NSMakeRange(1, 10);
NSRangeは単なる構造体であり、 Python の範囲オブジェクトとは異なります。
typedef struct _NSRange {
NSUInteger location;
NSUInteger length;
} NSRange;
そのため、メンバーにアクセスするにはforループを使用する必要があります。
NSUInteger num;
for(num = 1; num <= maxValue; num++ ){
// Do Something here
}
範囲のクラスで 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