创建一个用计数 N 初始化的 NSArray,所有的对象都是相同的 [英] Creating an NSArray initialized with count N, all of the same object
问题描述
我想创建一个具有相同值的对象(比如 NSNumber 都初始化为 1)的 NSArray,但计数基于另一个变量.除了处理 C 样式数组的初始化器之外,似乎没有办法使用 NSArray 的任何初始化器来做到这一点.
I want to create an NSArray with objects of the same value (say NSNumber all initialized to 1) but the count is based on another variable. There doesn't seem to be a way to do this with any of the intializers for NSArray except for one that deals with C-style array.
不知道有没有捷径可以做到这一点?
Any idea if there is a short way to do this?
这就是我要找的:
NSArray *array = [[NSArray alloc] initWithObject:[NSNumber numberWithInt:0]
count:anIntVariable];
NSNumber 只是这里的一个例子,它本质上可以是任何 NSObject.
NSNumber is just one example here, it could essentially be any NSObject.
推荐答案
我能够为此编写的最紧凑的代码是:
The tightest code I've been able to write for this is:
id numbers[n];
for (int x = 0; x < n; ++x)
numbers[x] = [NSNumber numberWithInt:0];
id array = [NSArray arrayWithObjects:numbers count:n];
这是可行的,因为您可以使用 Xcode 默认使用的 C99 创建运行时长度确定的 C 数组.
This works because you can create runtime length determined C-arrays with C99 which Xcode uses by default.
如果它们都是相同的值,您也可以使用 memset(尽管转换为 int 是顽皮的):
If they are all the same value, you could also use memset (though the cast to int is naughty):
id numbers[n];
memset(numbers, (int)[NSNumber numberWithInt:0], n);
id array = [NSArray arrayWithObjects:numbers count:n];
如果你知道你需要多少个对象,那么这段代码应该可以工作,尽管我还没有测试过:
If you know how many objects you need, then this code should work, though I haven't tested it:
id array = [NSArray arrayWithObjects:(id[5]){[NSNumber numberWithInt:0]} count:5];
这篇关于创建一个用计数 N 初始化的 NSArray,所有的对象都是相同的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!