开发者

Must child classes implement protocols to which their parents conform?

I have a class, MyClass, which implements the NSCopying protocol, a开发者_如何学JAVAnd I have a class, MyClassChild, which inherits from MyClass. MyClassChild does not implement the NSCopying protocol. The textbook I am reading says it must, however I can build successfully! Is the textbook wrong?

@interface MyClass : NSObject <NSCopying> {

}

@end

@implementation MyClass

-(id)copyWithZone:(NSZone *)zone
{
    return self;
}

@end

@interface MyClassChild : MyClass {

}

@end

@implementation MyClassChild

@end


When you don’t supply an implementation for the copyWithZone: method in MyClassChild, the class inherits the method implementation from its superclass (MyClass). This means that MyClassChild does conform to the NSCopying protocol. If MyClassChild needs to do something special when its instances are being copied, you should override copyWithZone: and do whatever needs to be done there. Hope that helps.

P.S. I hope you realize that returning self is not a good way to implement copyWithZone:?


MyClassChild inherits its implementation of NSCopying from MyClass. Even if you had specified

@interface MyClassChild : MyClass <NSCopying>

the compiler is clever enough to check if any of the super classes implement -copyWithZone:


You are absolutely right that NSCopying requires the object to implement copyWithZone. However, MyClass implements copyWithZone. So MyClassChild already an implementation of it by virtue of deriving from MyClass.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜