Implementing NSCopying in Subclass of Subclass

余生颓废 提交于 2019-11-30 08:06:19

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;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!