xcode 在子类的子类中实现 NSCopying
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4472904/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing NSCopying in Subclass of Subclass
提问by Craig Otis
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 answer.
我有一个小类层次结构,我在实现时遇到了麻烦copyWithZone:
。我已阅读 NSCopying 文档,但找不到正确答案。
Take two classes: Shapeand Square. Square is defined as:
拿两个类:Shape和Square。平方定义为:
@interface Square : Shape
No surprise there. Each class has oneproperty, Shape has a "sides" int, and Square has a "width" int. The copyWithZone:
methods are seen below:
不出意外。每个类都有一个属性,Shape 有一个“sides”int,Square 有一个“width”int。该copyWithZone:
方法被认为如下:
Shape
形状
- (id)copyWithZone:(NSZone *)zone {
Shape *s = [[Shape alloc] init];
s.sides = self.sides;
return s;
}
Square
正方形
- (id)copyWithZone:(NSZone *)zone {
Square *s = (Square *)[super copyWithZone:zone];
s.width = self.width;
return s;
}
Looking at the documentation, this seems to be the "right" way to do things.
查看文档,这似乎是做事的“正确”方式。
It is not.
它不是。
If you were to try to set/access the width property of a Square returned by the copyWithZone:
method, it would failwith an error similar to the one below:
如果您尝试设置/访问该copyWithZone:
方法返回的 Square 的 width 属性,它将失败并显示类似于以下错误的错误:
2010-12-17 11:55:35.441 Hierarchy[22617:a0f] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Shape setWidth:]: unrecognized selector sent to instance 0x10010c970'
Calling [super copyWithZone:zone];
in the Square method actually returns a Shape. It's a miracle you're even allowed to set the width property in that method.
调用[super copyWithZone:zone];
Square 方法实际上返回一个 Shape。您甚至可以在该方法中设置 width 属性,这真是一个奇迹。
That having been said, how does one implement NSCopyingfor subclasses in a way that does not make them responsiblefor copying the variables of its superclass?
话虽如此,如何以一种不让子类负责复制其超类变量的方式为子类实现 NSCopying?
回答by Craig Otis
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 wrongway, as I mentioned above:
copyWithZone:
超类 ( Shape) 中的实现不应该假设它是一个形状。所以,而不是错误的方式,正如我上面提到的:
- (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;
}