NSObject子类对象如果想要实现拷贝,就需要实现NSCopying,NSMutableCopying协议。
理论上说Copy实现的是浅拷贝:retain当前对象的指针,retainCount+1;
mutableCopy实现的是深拷贝:创建新的内存空间并返回地址,retainCount = 1;
个人猜测,之所以这么说因为系统的NSString,NSArray,NSDictionary等类的Copy实际是retain效果,这是Cocoa为了节省内存。
有点特殊的是,对于容器类,如NSArray,在使用mutableCopy时,只是对容器中的保存的指针进行了简单的值拷贝,并返回一个mutable类型的容器(换句话说容器是创建了新的空间但是其存储的对象指针还是原来容器存储的对象指针)。
对于自定义的类,我们实现的Copy跟系统的这种做法是有区别的,因为我们的Copy就是深拷贝,不是retain,但是对象的属性是浅拷贝。mutableCopy也是深拷贝,对象的属性也是深拷贝。
#import <Foundation/Foundation.h>
@interface Model : NSObject<NSCopying,NSMutableCopying>
@property(nonatomic , retain) NSString* itemId;
@property(nonatomic , retain) NSString* name;
- (instancetype)initWithDictionary:(NSDictionary*)dic;
@end
@implementation Model
-(id)copyWithZone:(NSZone *)zone
{
Model* model = [Model allocWithZone:zone];
model.itemId = self.itemId;
model.name = self.name;
return model;
}
- (id)mutableCopyWithZone:(NSZone *)zone
{
Model* model = [Model allocWithZone:zone];
model.itemId = [self.itemId mutableCopy];
model.name = [self.name mutableCopy];
return model;
}
测试下:
Model* model = [[Model alloc] initWithDictionary:@{@"id":@"111",@"name":@"haha"}];
Model* modelCopy = [model copy];
Model* modelMutableCopy = [model mutableCopy];
NSLog(@"model = %p copy = %p mutableCopy = %p",model,modelCopy,modelMutableCopy);
NSLog(@"model.item = %p copy.item = %p mutableCopy.item = %p",model.itemId,modelCopy.itemId,modelMutableCopy.itemId);
debug输出:
2015-05-06 21:51:34.747 CALayer+MyAnimation[1279:32457] model = 0x7fc4d0c157b0 copy = 0x7fc4d0f7e950 mutableCopy = 0x7fc4d0f90760
2015-05-06 21:51:34.747 CALayer+MyAnimation[1279:32457] model.item = 0x105848180 copy.item = 0x105848180 mutableCopy.item = 0x7fc4d2a1b4a0
对比上述指针,对象的地址都不同,但是copy跟源对象的item属性的指针都是一样的,mutableCopy的对象属性都不同,符合我们上述的要求。
最后问题来了,Copy是浅拷贝还是深拷贝?