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

2

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.

Diamagnetic answered 28/6, 2012 at 4:47 Comment(3)
This has also been discussed here: #9446065Goeger
And definitely check @Goeger answer. It is exactly the kind of dynamic solution you can do in ObjC.Sewellel
See also: https://mcmap.net/q/1414002/-looping-using-nsrange/…Detoxicate
P
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.

Pilch answered 28/6, 2012 at 5:44 Comment(1)
Note that with some more work, you can make this class extremely efficient.Pilch
R
0
NSRange range = NSMakeRange(0, 100);

You can iterate this range by:

NSUInteger loc;
for(loc = range.location; loc < range.length; loc++)
{ 
}
Residential answered 28/6, 2012 at 5:6 Comment(1)
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.Diamagnetic

© 2022 - 2024 — McMap. All rights reserved.