开发者

How to copy a NSMutableArray

开发者 https://www.devze.com 2023-02-28 13:17 出处:网络
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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号