7

Python は、次のように連続した数字でリストを作成できます。

numbers=range(1,10); // >> [1,2,3,4,5,6,7,8,9]

Objective-cでこれを実装する方法は?

4

4 に答える 4

11

あなたのステートメント「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 は必要ありません。

于 2012-08-03T11:51:47.013 に答える
6

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];

もっと頻繁に使用したい場合は、オプションでカテゴリに入れることができます。

于 2012-08-03T09:39:20.970 に答える
4

使用できます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
}
于 2012-08-03T09:48:28.087 に答える
1

範囲のクラスで NSArray をサブクラス化できます。NSArray のサブクラス化は非常に簡単です。

  • を呼び出す適切な初期化メソッドが必要[super init]です。と

  • オーバーライドする必要がありcountobjectAtIndex:

もっとできることがありますが、そうする必要はありません。以下は、いくつかのチェック コードが欠落しているスケッチです。

@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];

場合copyRangeArray通常のオブジェクトの配列になりますが、必要に応じてプロトコル メソッドNSNumberを実装することで回避できます。NSCopying

于 2012-08-03T10:26:31.007 に答える