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

佐手、 提交于 2020-01-06 20:06:45

问题


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.


回答1:


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.




回答2:


NSRange range = NSMakeRange(0, 100);

You can iterate this range by:

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


来源:https://stackoverflow.com/questions/11238211/what-is-the-most-efficient-way-to-generate-a-sequence-of-nsnumbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!