objective-c 如何动态填充 NSArray?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/839578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:30:58  来源:igfitidea点击:

How can I fill an NSArray dynamically?

iphoneobjective-cuikitnsmutablearraynsarray

提问by Thanks

I have a forloop. Inside that loop I want to fill up an NSArraywith some objects. But I don't see any method that would let me do that. I know in advance how many objects there are. I want to avoid an NSMutableArray, since some people told me that's a very big overhead and performance-brake compared to NSArray.

我有一个for循环。在那个循环中,我想NSArray用一些对象填充一个。但我没有看到任何方法可以让我这样做。我事先知道有多少对象。我想避免NSMutableArray,因为有些人告诉我,与NSArray.

I've got something like this:

我有这样的事情:

NSArray *returnArray = [[NSArray alloc] init];
for (imageName in imageArray) {
    UIImage *image = [UIImage imageNamed:imageName];
    //Now, here I'd like to add that image to the array...
}

I looked in the documentation for NSArray, but how do I specify how many elements are going to be in there? Or must I really use NSMutableArrayfor that?

我查看了 的文档NSArray,但是如何指定其中将包含多少个元素?或者我真的必须使用NSMutableArray它?

回答by Alnitak

Yes, you need to use an NSMutableArray:

是的,您需要使用一个NSMutableArray

int count = [imageArray count];
NSMutableArray *returnArray = [[NSMutableArray alloc] initWithCapacity:count];
for (imageName in imageArray) {
    UIImage *image = [UIImage imageNamed:imageName];
    [returnArray addObject: image];
    ...
}

EDIT - declaration fixed

编辑 - 声明已修复

回答by Kris

You'll need to use an NSMutableArrayfor that because adding is mutation and NSArrayis immutable.

您需要为此使用NSMutableArray,因为添加是变异,而NSArray是不可变的。

You could make a populated NSMutableArrayinto an NSArrayafterwards (see here for a discussion) but you won't be adding items to a regular old NSArrayanytime soon.

您可以将 a 填充NSMutableArrayNSArrayafter (请参阅此处的讨论),但您不会NSArray很快将项目添加到常规旧的。

回答by Wally Lawless

Would this be a good time to use an NSMutableArray?

这是使用NSMutableArray的好时机吗?

I know you mentioned that you would like to avoid it, but sometimes there's a reason for things like this.

我知道你提到过你想避免它,但有时这样的事情是有原因的。

回答by Rog

I would advise optimising only when you know NSMutableArrayiscausing you a performance hit but if it is, you can always create a static aray from a mutable array after you have populated it. It depends on if the performance hit is caused by you subsequent use of the NSMutableArrayor just by creating it.

我建议仅在您知道NSMutableArray导致性能下降时进行优化,但如果是,您始终可以在填充可变数组后从可变数组创建静态数组。这取决于性能下降是由您随后使用NSMutableArray还是仅通过创建它引起的。

My guess is that this isn't going to be the performance bottleneck on your app.

我的猜测是这不会成为您应用程序的性能瓶颈。