NSCopying协议和copy方法

不是所有的对象都支持 copy
需要继承NSCopying 协议(实现 copyWithZone: 方法)
同样,需要继承NSMutableCopying 协议才可以使用mutableCopy(实现 mutableCopyWithZone: 方法)

默认 NSObject没有实现这两个协议,但是 copy和mutableCopy这两个方法是NSObject定义的

这里要列举范例

//1.h
@interface  CommonObj : NSObject < NSCopying >
 
@end
 
@interface  MyCObj : NSObject < NSCopying >
@property  ( nonatomic  , copy ) CommonObj *obj;
@end
 
//1.m
@implementation  CommonObj
 
- ( id )init
{
     self  = [ super  init];
     if  ( self )
     {
     }
 
     return  self ;
}
 
- ( void )dealloc
{
     [ super  dealloc];
}
 
- ( id )copyWithZone:( NSZone  *)zone
{
     CommonObj *result = [[[ self  class ] allocWithZone:zone] init];
     return  result;
}
@end
 
@implementation  MyCObj
 
@synthesize  obj = _obj;
 
- ( id )init
{
     self  = [ super  init];
     if  ( self )
     {
         self ->_obj = nil ;
     }
 
     return  self ;
}
 
- ( void )dealloc
{
     if  ( self .obj)
         [ self ->_obj release];
 
     [ super  dealloc];
}
 
- ( id )copyWithZone:( NSZone  *)zone
{
     MyCObj *result = [[[ self  class ] allocWithZone:zone] init];
 
     result->_obj = [ self ->_obj copy ];
 
     return  result;
}
@end
 
//main.m
 
- ( void )Test
{
     CommonObj *a1 = [[CommonObj alloc] init];
     CommonObj *a2 = [a1 copy ];
 
     MyCObj *b1 = [[MyCObj alloc] init];
     MyCObj *b2 = [b1 copy ];
     [b2 release];
     [b1 release];
 
     [a2 release];
     [a1 release];
}

 打印上述对象的地址,就会发现地址各不相同,retaincount = 1;

这里要注意类似NSString的类,比如:NSArray

NSString *t1 = @"hello";
NSString *t2 = [t1 copy];

打印地址,两个地址一模一样;NSArray对象也是同样。之所以会是同一地址,估计在常量或不可变这个属性上

小结:
这个就是C++下的拷贝构造函数的另类描述,目的在于拷贝。至于实现的拷贝是深度拷贝还是浅度拷贝,这是由实现者设计

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值