问题
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