How do you deep copy a multidimensional NSMutableArray and its contents?

▼魔方 西西 提交于 2019-12-08 05:32:06

问题


I currently have a three dimensional NSMutableArray which I need to deep copy. However, it appears that the following code causes it and its contents to become immutable, since it causes NSInvalidArgumentException when I attempt to remove any objects from it.

NSMutableArray* copy = [[[NSMutableArray alloc] initWithArray:input copyItems:YES] autorelease];

How can I deep copy an array without causing it to become immutable?


回答1:


From the listing,

The copy imlementation of immutable classes usually returns the same object - because it's immutable there is no need to have a "real" copy. But you don't have to worry about this.

above from http://lists.apple.com/archives/cocoa-dev/2008/May/msg00172.html

So make sure before you add your input array, convert that input array into a mutable copy and then call the method.

Code:

NSMutableArray* mutableInput = [input mutableCopy];
NSMutableArray* copy = [[[NSMutableArray alloc] initWithArray:mutableInput copyItems:YES]autorelease];



回答2:


Use NSCoding

in .h file @interface classname : NSObject

in .m file

  • (id)copyWithZone:(NSZone *)zone { }


来源:https://stackoverflow.com/questions/10968021/how-do-you-deep-copy-a-multidimensional-nsmutablearray-and-its-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!