如何避免“不完全实现”部分基类中的警告 [英] How to avoid "incomplete implementation" warning in partial base class

查看:96
本文介绍了如何避免“不完全实现”部分基类中的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个协议,我的类需要实现,然后分解出一些常用的功能到一个基类,所以我这样做:

I have created a protocol that my classes need to implement, and then factored out some common functionality into a base class, so I did this:

@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< MyProtocol>。

In this way in my code I use a generic id<MyProtocol>.

代码工作(只要Base不直接使用),但是编译器在执行Base带有警告:

The code works (as long as Base is not used directly) but the compiler chokes at the end of the implementation of Base with a warning:

Incomplete implementation of class Base



的不完全实现

有办法避免这种警告,或者更好的方法是在Objc中获得这个部分实现的抽象基类行为?

Is there a way to avoid this warning or, even better, a more proper way to obtain this partially implemented abstract base class behavior in Objc?

推荐答案

可以想象这样做:

@implementation Base

- (void)bar
{
    if ([self class] == [Base class]) {
        [self doesNotRecognizeSelector:_cmd];
    }
}

@end

方式,你有一个实现,但默认情况下会引发异常。但是,如果派生类不小心调用 [super bar] 或不覆盖 bar 不会提高。如果这不是你想要的,你可以缩短到:

That way, you have an implementation, but by default it raises an exception. However, if a derived class accidentally calls [super bar] or does not override bar, then the exception won't be raised. If that's not what you want, you could just shorten it to:

@implementation Base

- (void)bar
{
    [self doesNotRecognizeSelector:_cmd];
}

@end

即使子类调用 [super bar] 或不覆盖 bar

In which case, an exception will be raised, even if a subclass calls [super bar] or does not override bar.

这篇关于如何避免“不完全实现”部分基类中的警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆