Objective-c的NSCopying协议

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

@protocol NSCopying

- (id)copyWithZone:(NSZone *)zone;

@end
zone参数是新对象将分配到的内存区,一般不用修改。

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

// Person
@interface Person : NSObject <NSCopying>

@property (nonatomic, copy) NSString* name;
@property int age ;

-(id) initWithName:(NSString*) pName andAge:(int) iAge ;
@end

Person类的实现。

// impl
@implementation Person

@synthesize name, age ;

//
-(id) initWithName:(NSString*) pName andAge:(int) iAge
{
    self = [super init] ;
    if ( self ) {
        self.name = pName ;
        self.age = iAge ;
    }
    return self ;
}

// 实现copyWithZone
-(id) copyWithZone:(NSZone *)zone
{
    NSLog(@"Person copyWithZone, class : %@.", [self.class description]) ;
    // 如果子类覆写该方法, 则[self class]的类型为子类型,如果直接使用
    // [[Person allocWithZone:zone] init], 则子类覆写时会出错.
    Person* per = [[[self class] allocWithZone:zone] init] ;
    per.name = self.name ;
    per.age = self.age ;
    return per ;
}

@end
在copyWithZone函数中创建了一个对象,并且将属性挨个拷贝给新的对象。 注意新对象per的创建方法
[[[self class] allocWithZone:zone] init] ;
而不是
[[Person allocWithZone:zone] init] ;

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


例如Student类继承自Person类。

// subclass, Student
@interface Student : Person
// 班级名
@property (nonatomic, copy) NSString* className ;

@end

Student的实现,覆写copyWithZone函数。

// Student实现
@implementation Student

// 覆写copyWithZone,
-(id) copyWithZone:(NSZone *)zone
{
    // 1、先调用父类的copyWithZone函数
    Student* per = [super copyWithZone:zone] ;
    // 2、再设置className
    per.className = self.className ;
    NSLog(@"Student copyWithZone") ;
    return per ;
}

@end

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值