objective-c NSArray 添加元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778465/
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:26:02  来源:igfitidea点击:

NSArray adding elements

objective-cnsarray

提问by saikamesh

I have to create a dynamic NSArray, that is, I don't know the size of the array or what elements the array is going to have. The elements need to be added to the array dynamically. I looked at the NSArray class reference. There is a method called arrayWithObjects, which should be used at the time of initializing the array itself. But I don't know how to achieve what I need to do.

我必须创建一个动态的 NSArray,也就是说,我不知道数组的大小或数组将包含哪些元素。元素需要动态添加到数组中。我查看了 NSArray 类参考。有一个方法叫做arrayWithObjects,应该在初始化数组本身的时候使用。但我不知道如何实现我需要做的事情。

I need to do some thing like the following:

我需要做一些如下的事情:

NSArray *stringArray = [[NSArray init] alloc] ;  
for (int i = 0; i < data.size; i++){  
    stringArray.at(i) = getData(i);
}

回答by pgb

If you create an NSArrayyou won't be able to add elements to it, since it's immutable. You should try using NSMutableArrayinstead.

如果您创建一个,NSArray您将无法向其添加元素,因为它是不可变的。您应该尝试使用NSMutableArray

Also, you inverted the order of allocand init. alloccreates an instance and initinitializes it.

此外,您颠倒了alloc和的顺序initalloc创建一个实例并init初始化它。

The code would look something like this (assuming getDatais a global function):

代码看起来像这样(假设getData是一个全局函数):

NSMutableArray *stringArray = [[NSMutableArray alloc] init];
for(int i=0; i< data.size; i++){
   [stringArray addObject:getData(i)];
}

回答by Danil

Here is another way to add object in array if you are working with immutable array. Which is thread safe.

如果您使用的是不可变数组,这是在数组中添加对象的另一种方法。这是线程安全的。

You can use arrayByAddingObjectmethod. Some times it's much better. Here is discussion about it: NSMutableArray vs NSArray which is better

您可以使用arrayByAddingObject方法。有时会好得多。这是关于它的讨论:NSMutableArray vs NSArray哪个更好

回答by Darius Miliauskas

Convert your NSArray to NSMutableArray, and then you can add values dynamically:

将您的 NSArray 转换为 NSMutableArray,然后您可以动态添加值:

NSMutableArray *mutableStringArray = [stringArray mutableCopy];
[mutableStringArray addObject:@"theNewElement"];