objective-c - 如何避免部分基类中的 "incomplete implementation"警告

标签 objective-c oop coding-style

我已经创建了我的类需要实现的协议(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/

相关文章:

ios - 下载多个文件时如何避免内存警告

oop - 应用层与 UI

java - 单击 JButton 后创建延迟关闭 JFrame

php - 在 PHP 中跨类共享类实例

C++:指示一个函数可能会抛出

python - M 类 : or class M():?

iphone - 对某些类使用类别,而不是对完整代码使用类别

php - AFNetworking 2.0图片上传和JSON返回错误

iOS:访问4.0以下的OlderBluetoothDevice

sql - 在 Rails 模型中编写大型 SQL 的更好方法?