问题
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