copy一个数组的方法


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.





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值