简体   繁体   English

如何复制NSMutableArray

[英]How to copy a NSMutableArray

I would simply like to know how to copy a NSMutableArray so that when I change the array, my reference to it doesn't change. 我只想知道如何复制NSMutableArray,以便在更改数组时,对它的引用不会更改。 How can I copy an array? 如何复制数组?

There are multiple ways to do so: 有多种方法可以这样做:

NSArray *newArray = [NSMutableArray arrayWithArray:oldArray];

NSArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray] autorelease];

NSArray *newArray = [[oldArray mutableCopy] autorelease];

These will all create shallow copies , though. 不过,这些都会创建浅表副本

( Edit: If you're working with ARC, just delete the calls to autorelease .) 编辑:如果您使用的是ARC,只需删除对autorelease的调用即可。)

For deep copies use this instead: 对于深层副本,请使用以下代码:

NSMutableArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray copyItems:YES] autorelease];

Worth noting: For obvious reasons the latter will require all your array's element objects to implement NSCopying . 值得注意的是:出于明显的原因,后者将需要您数组的所有元素对象来实现NSCopying

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

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