I would simply like to know how to copy a NSMutableArray so that when I change the array, my reference to it d开发者_C百科oesn't change. 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
.)
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
.
精彩评论