简体   繁体   中英

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

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?

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];

Use NSCoding

in .h file @interface classname : NSObject

in .m file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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