简体   繁体   English

如何将 NSArray 复制到另一个 NSArray?

[英]How to copy NSArray to another NSArray?

I have many different NSArrays , and according to the users choice I want one of them to be copied to a new NSArray .我有许多不同的NSArrays ,根据用户的选择,我希望将其中一个复制到新的NSArray How do I copy one NSArray to another?如何将一个NSArray复制到另一个?

There can be several ways for this-有几种方法可以做到这一点——

  1. array1 = [array2 copy];

  2. Use initWithArray method.使用initWithArray方法。

  3. You can also use initWithArray:copyItems: method.您还可以使用initWithArray:copyItems:方法。 (This if for NSMutableArray ) (这对于NSMutableArray

you can use the你可以使用

NSArray *_newArray = [NSArray arrayWithArray:_oldArray];

or if you prefer better, you can use:或者,如果您更喜欢,可以使用:

NSArray *_newArray = [[NSArray alloc] initWithArray:_oldArray];

(in that case the object of the first array won't be copied, that get only a retain front he second NSArray , you can remove the object from any array it won't affect the other array, but if you change any object in any NSArray it will be changed in the other one as well because there is both of the old and the new array is working with the same instance of the objects.) (在这种情况下,第一个数组的对象不会被复制,只有在第二个NSArray前面保留一个对象,您可以从任何数组中删除该对象,它不会影响另一个数组,但是如果您更改了任何对象任何 NSArray 也将在另一个 NSArray 中更改,因为旧数组和新数组都在使用相同的对象实例。)

if your plan is to make another instance of the old objects in the new array:如果您的计划是在新数组中创建旧对象的另一个实例:

NSArray *_newArray = [[NSArray alloc] initWithArray:_oldArray copyItems:true];

if you are using the ARC, you won't need to do anything else, if you are not, in the case of both -initWithArray: or -initWithArray:copyItems: you should use the [_newArray release];如果您使用的是ARC,你将不需要到别的做任何事情,如果你不是,在这两种情况下-initWithArray:-initWithArray:copyItems:你应该使用[_newArray release]; to release the array after you don't want to use anymore.在您不想再使用后释放阵列。

As well as

NSArray *newArray = [oldArray copy];

if you need to add/remove from the new array, the simplest way to make a mutable copy is:如果您需要从新数组中添加/删除,制作可变副本的最简单方法是:

NSMutableArray *editableArray = [oldArray mutableCopy];

The above functions both make shallow copies, for deep copy it's as @holex and @rishi mentioned上面的函数都是浅拷贝,深拷贝就像@holex 和@rishi 提到的

NSArray *newArray = [[NSArray alloc] initWithArray:oldArray copyItems:true];
NSMutableArray *editableArray = [[NSMutableArray alloc] initWithArray:oldArray copyItems:true];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM