您的位置:首页 > 运维架构

实现<NSCopying>协议

2015-02-25 10:28 260 查看
如果你尝试复制自己的一个类,例如分数类

#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的成功复制,且地址不是一样的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐