Implementing NSCopying in Subclass of Subclass

前端 未结 1 1736
故里飘歌
故里飘歌 2020-12-31 00:14

I have a small class hierarchy that I\'m having trouble implementing copyWithZone: for. I\'ve read the NSCopying documentation, and I can\'t find the correct an

相关标签:
1条回答
  • 2020-12-31 00:24

    One of those things you realize right after asking...

    The implementation of copyWithZone: in the superclass (Shape) shouldn't be assuming it's a Shape. So instead of the wrong way, as I mentioned above:

    - (id)copyWithZone:(NSZone *)zone {
        Shape *s = [[Shape allocWithZone:zone] init];
        s.sides = self.sides;
        return s;
    }
    

    You should instead use:

    - (id)copyWithZone:(NSZone *)zone {
        Shape *s = [[[self class] allocWithZone:zone] init]; // <-- NOTE CHANGE
        s.sides = self.sides;
        return s;
    }
    
    0 讨论(0)
提交回复
热议问题