NSCopying 使用(转载)

在Objective-c中, 某个类遵守了NSCopying协议就代表这个类支持[obj copy]操作。在没有实现NSCopying协议的情况下调用对象的copy函数则会出现异常。NSCopying协议只有一个函数,即copyWithZone, 声明如下 :

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. @protocol NSCopying  
  2.   
  3. - (id)copyWithZone:(NSZone *)zone;  
  4.   
  5. @end  
zone参数是新对象将分配到的内存区,一般不用修改。

遵守NSCopying协议则需要在@implementation中实现copyWithZone函数。

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Person  
  2. @interface Person : NSObject <NSCopying>  
  3.   
  4. @property (nonatomiccopy) NSString* name;  
  5. @property int age ;  
  6.   
  7. -(id) initWithName:(NSString*) pName andAge:(int) iAge ;  
  8. @end  

Person类的实现。

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // impl  
  2. @implementation Person  
  3.   
  4. @synthesize name, age ;  
  5.   
  6. //  
  7. -(id) initWithName:(NSString*) pName andAge:(int) iAge  
  8. {  
  9.     self = [super init] ;  
  10.     if ( self ) {  
  11.         self.name = pName ;  
  12.         self.age = iAge ;  
  13.     }  
  14.     return self ;  
  15. }  
  16.   
  17. // 实现copyWithZone  
  18. -(id) copyWithZone:(NSZone *)zone  
  19. {  
  20.     NSLog(@"Person copyWithZone, class : %@.", [self.class description]) ;  
  21.     // 如果子类覆写该方法, 则[self class]的类型为子类型,如果直接使用  
  22.     // [[Person allocWithZone:zone] init], 则子类覆写时会出错.  
  23.     Person* per = [[[self class] allocWithZone:zone] init] ;  
  24.     per.name = self.name ;  
  25.     per.age = self.age ;  
  26.     return per ;  
  27. }  
  28.   
  29. @end  
在copyWithZone函数中创建了一个对象,并且将属性挨个拷贝给新的对象。 注意新对象per的创建方法
[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. [[[self class] allocWithZone:zone] init] ;  
而不是
[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. [[Person allocWithZone:zone] init] ;  

这是因为如果有子类覆写了copyWithZone函数,那么在子类对象被拷贝时会调用Person类的copyWithZone函数, 如果硬编码类型为Person, 则创建的对象为Person类型, 而不是子类型,因此会出现异常。而[self class]则会获取正确的类型, 并且创建出正确的对象,避免异常出现。


例如Student类继承自Person类。

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // subclass, Student  
  2. @interface Student : Person  
  3. // 班级名  
  4. @property (nonatomiccopy) NSString* className ;  
  5.   
  6. @end  

Student的实现,覆写copyWithZone函数。

[objc]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. // Student实现  
  2. @implementation Student  
  3.   
  4. // 覆写copyWithZone,  
  5. -(id) copyWithZone:(NSZone *)zone  
  6. {  
  7.     // 1、先调用父类的copyWithZone函数  
  8.     Student* per = [super copyWithZone:zone] ;  
  9.     // 2、再设置className  
  10.     per.className = self.className ;  
  11.     NSLog(@"Student copyWithZone") ;  
  12.     return per ;  
  13. }  
  14.   
  15. @end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值