生成 NSNumbers 序列的最有效方法是什么? [英] What is the most efficient way to generate a sequence of NSNumbers?

查看:69
本文介绍了生成 NSNumbers 序列的最有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当简单的 Python 内置函数,例如:x = range(0,100)如何使用objective-c方法完成同样的壮举?肯定有比 NSMutableArray 和 for 循环更好的东西:

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]];
}

是的,我知道这样做很可能不是我实际上想做的(例如:python 中的 xrange),但请幽默一下我的好奇心.=)

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. =)

说明:我想要一个包含 NSNumbers 序列的 NSArray,以便可以进一步处理该数组,例如通过对元素进行混洗或按外部指标排序.

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.

推荐答案

如果你想要这样的数组,你可能想要做你自己特定的 NSArray 子类.

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

之后,您可以重写一些其他 NSArray 方法,使您的类更高效.

After that, you can override some other NSArray methods to make your class more efficient.

这篇关于生成 NSNumbers 序列的最有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆