0

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.

Jeremy Jay
  • 1,323
  • 13
  • 15
  • This has also been discussed here: http://stackoverflow.com/questions/9445565/how-to-convert-a-range-to-nsarray-in-objective-c/9445843#9445843 – Monolo Jun 28 '12 at 05:35
  • And definitely check @Monolo answer. It is exactly the kind of dynamic solution you can do in ObjC. – Rob Napier Jun 28 '12 at 05:47
  • See also: http://stackoverflow.com/questions/8320987/looping-using-nsrange/8321037#8321037 – jscs Jun 28 '12 at 06:41

2 Answers2

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.

Julien
  • 3,427
  • 20
  • 22
0
NSRange range = NSMakeRange(0, 100);

You can iterate this range by:

NSUInteger loc;
for(loc = range.location; loc < range.length; loc++)
{ 
}
Jeff Hellman
  • 2,117
  • 18
  • 17
  • I guess I'll clarify my question, I want an NSArray containing all the elements. NSRange doesn't seem to give any utility over a basic for loop for this. – Jeremy Jay Jun 28 '12 at 05:27