简体   繁体   中英

What is the most efficient way to generate a sequence of NSNumbers?

It's a fairly simple builtin in python for example: x = range(0,100) How can I accomplish the same feat using objective-c methods? Surely there is something better than a NSMutableArray and a for-loop:

NSMutableArray *x = [NSMutableArray arrayWithCapacity:100];
for(int n=0; n<100; n++) {
    [x addObject:[NSNumber numberWithInt:n]];
}

Yes, I am aware that doing this is most likely not what I actually want to do (ex: xrange in python), but humor my curiosity please. =)

Clarification: I would like a NSArray containing a sequence of NSNumbers, so that the array could be further processed for example by shuffling elements or sorting by an external metric.

If you want such an array, you might want to do your own specific subclass of NSArray.

A very basic implementation example would look like:

@interface MyRangeArray : NSArray
{
@private
    NSRange myRange;
}

+ (id)arrayWithRange:(NSRange)aRange;
- (id)initWithRange:(NSRange)aRange;

@end

@implementation MyRangeArray

+ (id)arrayWithRange:(NSRange)aRange
{
    return [[[self alloc] initWithRange:aRange] autorelease];
}

- (id)initWithRange:(NSRange)aRange
{
    self = [super init];
    if (self) {
        // TODO: verify aRange limits here
        myRange = aRange;
    }
    return self;
}

- (NSUInteger)count
{
    return myRange.length;
}

- (id)objectAtIndex:(NSUInteger)index
{
    // TODO: add range check here
    return [NSNumber numberWithInteger:(range.location + index)];
}

@end

After that, you can override some other NSArray methods to make your class more efficient.

NSRange range = NSMakeRange(0, 100);

You can iterate this range by:

NSUInteger loc;
for(loc = range.location; loc < range.length; loc++)
{ 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM