objective-c - Objective C 中的协议(protocol)继承

标签 objective-c protocols

我有一个项目,其中包含一个协议(protocol)、一个实现该协议(protocol)的类和一个实现类的子类。这是我们的生产应用程序。

@protocol ProductionProtocol<NSObject>
@property (nonatomic, retain) NSString *role;
@end

@interface BaseProduction : NSObject<ProductionProtocol>
NSString *role;
@end

@implementation BaseProduction
@synthesize role;
@end

@interface Production : BaseProduction
@end

@implementation Production
@end

我还有一个概念验证 (POC) 应用程序,它是作为一个包含生产应用程序的单独项目实现的。在 POC 应用程序中,我有一个扩展生产协议(protocol)的协议(protocol),以及一个扩展生产类的类。

@protocol POCProtocol<ProductionProtocol>
-(void)cancel;
@end

@interface POC : Production<POCProtocol>
@end

@implementation POC
-(void)cancel{...}
@end

请注意,在 ProductionProtocol 中,我有一个 NSString 角色,它是在 BaseProduction 接口(interface)/类中声明和实现的。在 POC 中,我有一个方法“取消”,它在协议(protocol)中声明,但不在接口(interface)/类中。

所以这是我的问题:我的类结构是这样设置的,我收到了这个警告:

Property 'role' requires method '-role' to be defined - use @synthesize, @dynamic or provide a method implementation

我不明白为什么我会收到此警告。由于综合属性位于基类中,因此 POC 类应该可以使用它们 - 并且快速测试似乎可以确认它们是可用的。那我在这里做错了什么?

最佳答案

Objective-C 没有官方语言定义,但根据 Apple :

When a class adopts a protocol, it must implement the required methods the protocol declares, as mentioned earlier. In addition, it must conform to any protocols the adopted protocol incorporates. If an incorporated protocol incorporates still other protocols, the class must also conform to them. A class can conform to an incorporated protocol using either of these techniques:

  • Implementing the methods the protocol declares
  • Inheriting from a class that adopts the protocol and implements the methods

但是,有报告称 GCC 无法识别该属性在合并协议(protocol)中并在父类(super class)中实现。您可以将编译器更改为 Clang,据报道它以指定的方式处理此问题,或者您可以只使用 @dynamic 告诉编译器将在运行时提供该属性的实现(在这种情况下,通过从父类(super class)继承)。

关于objective-c - Objective C 中的协议(protocol)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5435604/

相关文章:

swift - 代码维护在委托(delegate)和回调模式

ios - NSString stringWithCString不显示特殊字符吗?

ios - 循环后如何在主队列上重新加载表(Objective-c)

desktop - 如何检测远程计算机是否正在运行 RDP?

swift - 比较 2 个结构/对象实现相同的协议(protocol)?

java - Xmodem协议(protocol)在Java中的实现

hex - 任何用于将十六进制转储转换为人类可读形式的通用实用程序或库?

ios - 如何从钥匙串(keychain)中删除 nsdictionary 以进行替换

objective-c - 在 Objective-C 中使用 Swift 扩展方法

ios - 持久化指向对象的指针