copy一个数组的方法

来源:互联网 发布:淘宝客公众号 编辑:程序博客网 时间:2024/05/27 14:13


NSArray *rr = [NSArray arrayWithObjects:@"aa", @"ef", @"va", nil];

NSArray *r1 = rr;        //rr的引用计数还是1,因为NSArray是一个常量


NSMutableArray *dd = [NSMutableArray arrayWithObjects:@"e", @"v", nil];

NSMutableArray *r2 = dd;        //rr的引用计数还是2,因为NSMutableArray不是一个常量


NSArray *newArray = [NSMutableArray arrayWithArray:oldArray];
NSArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray] autorelease];
NSArray *newArray = [[oldArray mutableCopy] autorelease];
NSMutableArray *newArray = [[[NSMutableArray alloc] initWithArray:oldArray copyItems:YES] autorelease];
NSArray *_newArray = [NSArray arrayWithArray:_oldArray];

or if you prefer better, you can use:

NSArray *_newArray = [[NSArray alloc] initWithArray:_oldArray];

(in that case the object of the first array won't be copied, that get only a retain front he second NSArray, you can remove the object from any array it won't affect the other array, but if you change any object in any NSArray it will be changed in the other one as well because there is both of the old and the new array is working with the same instance of the objects.)

if your plan is to make another instance of the old objects in the new array:

NSArray *_newArray = [[NSArray alloc] initWithArray:_oldArray copyItems:true];

if you are using the ARC, you won't need to do anything else, if you are not, in the case of both -initWithArray: or -initWithArray:copyItems: you should use the [_newArray release]; to release the array after you don't want to use anymore.





原创粉丝点击