xcode 如何复制 NSMutableArray
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5766264/
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
How to copy a NSMutableArray
提问by Blane Townsend
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. How can I copy an array?
我只想知道如何复制 NSMutableArray 以便当我更改数组时,我对它的引用不会改变。如何复制数组?
回答by Regexident
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 copiesuse 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
.