簡體   English   中英

Objective-C數組中的連續數字,如Python中的range()

[英]Continuous numbers in Objective-C array like range() in Python

Python可以創建一個包含連續數字的列表,如下所示:

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

如何在Objective-c中實現這一點?

閱讀你的陳述“只需要一個帶有連續數字的數組,我不想用循環初始化它”讓我問:對你來說更重要的是:擁有一個array或擁有代表連續范圍的“ 東西 ” (自然)數字。 看看NSIndexSet它可能接近你想要的。 你初始化它

[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(1,9)]; 

迭代這個集就像迭代數組一樣簡單,不需要NSNumbers。

Objective-C(或實際基礎)對此沒有特殊功能。 你可以使用:

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

  • 你需要覆蓋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];

如果copy RangeArray ,它將成為NSNumber對象的正常數組,但如果您希望通過實現NSCopying協議方法,則可以避免。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM