What is the most efficient way to generate NSNumbers sequences?

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

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

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

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

0
source share
2 answers

If you need such an array, you might want to create your own subclass of NSArray.

The simplest implementation example would look like this:

 @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.

+1
source
 NSRange range = NSMakeRange(0, 100); 

You can iterate over this range:

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

Source: https://habr.com/ru/post/922042/


All Articles