实现<NSCopying>协议

如果你尝试复制自己的一个类,例如分数类

#import "Fraction.h"

@implementation Fraction

- (instancetype)initWithFirst:(NSInteger)first second:(NSInteger)second
{
    self = [self init];
    if (self) {
        [self setFirst:first];
        [self setSecond:second];
    }
    return self;
}

+ (instancetype)fractionWithFirst:(NSInteger)first second:(NSInteger)second
{
    Fraction *f = [[Fraction alloc] initWithFirst:first second:second];
    return f;
}

- (void)printFraction
{
    NSLog(@"%ld / %ld", [self first], [self second]);
}

@end

这样去复制

newFraction = [myFraction mutableCopy];

你会得到这样的错误

*** -[AddressBook copyWithZone:]: selector not recognized
*** Uncaught exception:
*** -[AddressBook copyWithZone:]: selector not recognized

为了让自定义类实现复制方法,需要根据< NSCopying >协议实现一到两个方法

- (id)copyWithZone:(NSZone *)zone
{
    Fraction *f = [[Fraction alloc] init];
    [f setFirst:_first];
    [f setSecond:_second];
    return f;
}

现在来测试下

    Fraction *f1 = [Fraction fractionWithFirst:2 second:3];
    Fraction *f2 = [f1 copy];
    [f2 setFirst:1];
    [f2 setSecond:2];
    [f1 printFraction];
    NSLog(@"%p", f1);
    [f2 printFraction];
    NSLog(@"%p", f2);

控制台输出

 2 / 3
 0x100200b80
 1 / 2
 0x100202ba0

可见f2是f1的成功复制,且地址不是一样的

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值