我已经创建了我的类需要实现的协议(protocol),然后将一些通用功能分解到基类中,所以我这样做了:
@protocol MyProtocol
- (void) foo;
- (void) bar;
@end
@interface Base <MyProtocol>
@end
@interface Derived_1 : Base
@end
@interface Derived_2 : Base
@end
@implementation Base
- (void) foo{
//something foo
}
@end
@implementation Derived_1
- (void) bar{
//something bar 1
}
@end
@implementation Derived_2
- (void) bar{
//something bar 2
}
@end
通过这种方式,在我的代码中我使用了通用 id
代码有效(只要不直接使用 Base)但编译器在 Base 的实现结束时阻塞并发出警告:
Incomplete implementation of class Base
有没有办法避免这个警告,或者更好的是,有更合适的方法在 Objc 中获得这个部分实现的抽象基类行为?
最佳答案
你可以想象做这样的事情:
@implementation Base
- (void)bar
{
if ([self class] == [Base class]) {
[self doesNotRecognizeSelector:_cmd];
}
}
@end
这样,您就有了一个实现,但默认情况下它会引发异常。但是,如果派生类不小心调用了 [super bar]
或没有覆盖 bar
,则不会引发异常。如果这不是您想要的,您可以将其缩短为:
@implementation Base
- (void)bar
{
[self doesNotRecognizeSelector:_cmd];
}
@end
在这种情况下,即使子类调用[super bar]
或没有覆盖bar
,也会引发异常。
关于objective-c - 如何避免部分基类中的 "incomplete implementation"警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2854522/