iphone - XCode 错误警告 "does not implement the X protocol"

标签 iphone xcode warnings protocols

在我的项目中,我有 3 个类,我们称它们为 Apple、Orange 和 Pear。

Apple 和 Orange 都有委托(delegate)属性。
它们都在名为 AppleDelegate 和 OrangeDelegate 的头文件中定义了协议(protocol)。
它们每个都有具有相似签名的初始值设定项:

- (id)initWithDelegate:(id<AppleDelegate>)delegate
- (id)initWithDelegate:(id<OrangeDelegate>)delegate

Pear 实现 OrangeDelegate 并定义如下:

@interface Pear : NSObject <OrangeDelegate>

在 Pear 内部,我调用此电话:

Orange *anOrange = [[[Orange alloc] initWithDelegate:self] autorelease];

这会导致编译器警告:

Class 'Pear' does not implement the 'AppleDelegate' protocol

在我看来,编译器无法识别初始化程序中的协议(protocol)。换句话说,它只识别以下两者的签名:

- (id)initWithDelegate:(id)delegate

因为当我在 Pear 中单击初始化器上的“跳转到定义”时,它会显示这两个类作为选项。

除了重命名我的方法之外,还有什么方法可以纠正此警告吗?

最佳答案

问题是'alloc'是一个继承自NSObject的方法,定义为返回类型'id'。所以如下:

[Orange alloc]

计算结果为“id”类型的对象。然后,当您对该对象调用 initWithDelegate 时,编译器不知道该类型,在这种情况下会猜测错误的类型。因此您可以通过以下方式消除警告:

Orange *anOrange = [[(Orange *)[Orange alloc] initWithDelegate:self] autorelease];

所以,基本上,这是因为构造函数不是 Objective-C 中的语言级功能,而只是一种约定。

编辑:见下文;我想另一个解决方案是添加:

+ (Orange *)alloc;

对于 Orange,这不会比以下更复杂:

+ (Orange *)alloc
{
    return [super alloc];
}
我想这在一定程度上是一个设计决策——类是否应该负责知道它们的构造函数方法可能与其他类的名称冲突,或者导入具有相同构造函数的多个类定义的文件是否应该负责消除歧义。尽管语法的简单外观可能是关键。

关于iphone - XCode 错误警告 "does not implement the X protocol",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4221184/

相关文章:

iphone - 知道由于 Dismissal(不是 segue)而出现 ViewController

iphone - Instruments 说我有内存泄漏,但我没有看到它

c - 警告 : Suspicious pointer-to-pointer conversion (area too small) with lint

android - "Unrecognized App"安卓支付接口(interface)

ios - xcode 8模拟器先白后黑

python - Specifically silent Pandas SettingWithCopyWarning 使用警告上下文管理器?

iphone - iTunes 认为两个不同的应用程序是同一个

ios - 如何从 Web Link 将 .ipa 文件安装到 iPhone?

iphone - 如果我的应用程序使用 "aluminum look"作为其图标,它会被拒绝吗?

c++ - Release模式下的 Xcode 无法编译 <immintrin.h> - 提示 __builtin_ia32_emms()