天天看点

对象拷贝copy与mutableCopy

对象的拷贝有两种函数:copy和mutableCopy,它们的返回值分别是copyWithZone和mutableCopyWithZone的结果。

1. copyWithZone, 其说明有一段

Discussion

The returned object is implicitly retained by the sender, who is responsible for releasing it. The copy returned is immutable if the consideration “immutable vs. mutable” applies to the receiving object; otherwise the exact nature of the copy is determined by the class. 

如果是区分可变和不可变的类型,copy函数返回的对象是不可变的,比如NSMutableArray(可变数组)和NSArray(不可变数组),不管是哪种类型调用的copy方法,其返回的都是不可变类型:

NSMutableArray* mArray = [NSMutableArray arrayWithObjects:@"hi",nil];//可变数组

NSArray* array = [NSArray arrayWithObjects:@"ha", nil];//不可变数组

NSArray* arrayCopy1 = [mArray copy];//可变数组对象调用的copy方法返回的是不可变数组

NSArray* arrayCopy2 = [array copy];//不可变数组对象调用copy方法返回的也是不可变数组

当然也可以用可变类型去接收,但对象指针实质是指向的不可变对象,所以一旦调用可变类型的方法会报错,如

NSMutableArray* mArray2 = [mArray copy];

[mArray2 addObject:@"add"];//编译器检测不出来,但程序会崩掉

2. mutableCopyWithZone, 其说明也对可变不可变有解释

Discussion

The returned object is implicitly retained by the sender, which is responsible for releasing it. The copy returned is mutable whether the original is mutable or not.

不论调用mutableCopyWithZone的对象是可变还是不可变类型,其返回的都是可变类型

NSMutableArray* mArray4 = [mArray1  mutableCopy];//返回可变数组

NSMutableArray* mArray5 = [array mutableCopy];//不可变数组对象调用的mu tableCopy返回的也是可变数组

3. 而对于不区分可变和不可变对封装类型来说,它们只实现了copy方法,不存在mutableCopy方法,如

NSNumber* num = @123;

//[num mutableCopy];//方法调用失败,不存在这个方法

NSNumber* num2 = [num copy];//正常