深复制:父类已经加入了NSCopying协议,它的子类该怎么重载copyWithZone?

侠隐 发布于 2016/05/30 12:06
阅读 292
收藏 0

大家好,我是刚学objective-c的,在书里看到这样的一句话:


如果编写一个类的 copyWithZone: 方法,而该烊的超类也实现了<NSCopying>协议,那么应该先调用超类的 copy 方法以复制继承来的实例变量,然后加入自己的代码已复制想要添加到该类中任何附加的实例变量

于是我尝试去做这件事:代码如下:

#import <Foundation/Foundation.h>

@interface Fraction: NSObject <NSCopying>

@property int numerator,denominator;

@end

@implementation Fraction

-(id) copyWithZone:(NSZone *)zone
{
    Fraction* newFract =  [[[self class] allocWithZone: zone] init];
    newFract.numerator = self.numerator;
    newFract.denominator = self.denominator;
    return newFract;
}

@end


@interface Fraction2: Fraction
@property int sum;
@end

@implementation Fraction2

-(id) copyWithZone:(NSZone *)zone
{
    //这里就是我对上面那句话的做法,但我发现这句话运行的时候抛异常了 返回newFract为nil
    Fraction2 *newFract = [super copy];
    
    newFract.sum = self.sum;
    return newFract;
}

@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        Fraction *f1 = [[Fraction alloc] init];
        Fraction *f2;
        
        [f1 setNumerator:1];
        [f1 setDenominator:2];
        
        f2 = [f1 copy];
        
        [f2 setNumerator:3];
        [f2 setDenominator:5];
        
        NSLog(@"%i %i",f1.numerator,f1.denominator);
        NSLog(@"%i %i",[f2 numerator],[f2 denominator]);
        
        Fraction2* f3 = [[Fraction2 alloc] init];
        Fraction2* f4;
        
        [f3 setNumerator:10];
        [f3 setDenominator:15];
        [f3 setSum:25];
        
        f4 = [f3 copy];
        
        NSLog(@"before %i %i %i",[f4 numerator],[f4 denominator],[f4 sum]);
        
        
        [f4 setSum:34];
        [f4 setDenominator:15];
        [f4 setNumerator:19];
        
        NSLog(@"%i %i %i",f3.numerator,f3.denominator,f3.sum);
        NSLog(@"%i %i %i",[f4 numerator],[f4 denominator],[f4 sum]);
        
    }
    return 0;
}
我的做法在上面的注释那里写了,请问我该怎么修改,可能问题比较简单,希望大家帮一下我,谢谢


已解决: 使用[super copyWithZone:zone]替代

加载中
返回顶部
顶部