协议符合错误 Objective C

Protocol conformation error Objective C

DataProvider.h

@protocol NewDataProviderProtocol 

- (void)fetchNewData;

@end

SomeClass

#import DataProvider.h
@interface SomeClass :NSObject <NewDataProviderProtocol>

@end

当我尝试使 SomeClass 符合 NewDataProviderProtocol 时,它说,

No type or protocol named 'NewDataProviderProtocol'

这很奇怪,因为我已经导入了声明协议的 header DataProvider.h。

所以我在 SomeClass 的接口之前转发声明 NewDataProviderProtocol 但是 xcode 警告

Cannot find definition for **NewDataProviderProtocol**

这是什么原因和解决方法?

有两件事要改变:

像这样更改定义:

@protocol NewDataProviderProtocol <NSObject>    
- (void)fetchNewData;    
@end

为什么? Why tack a protocol of NSObject to a protocol implementation

仅在 SomeClass.m 中导入 DataProvider。您始终可以在实现文件中创建 SomeClass 的扩展,您可以在其中绑定协议以符合特定的 class.

@interface SomeClass ()<NewDataProviderProtocol>

@end

为什么?这是最佳实践。并克服前向 class 声明错误。例如。 Objective-C: Forward Class Declaration

一个。原因

您可能有一个包含周期,因为您也将 SomeClass.h 导入 DataProvider.h。这会导致未声明的标识符。

为什么会这样?让我们举个例子:

// Foo.h
#import "Bar.h"
@interface Foo : NSObject 
…// Do something with Bar 
@end


// Bar.h
#import "Foo.h"
@interface Bar : NSObject 
…// Do something with Foo 
@end

如果你编译,比方说Foo.h,预编译器会展开这个:

他得到……:

// Foo.h
#import "Bar.h"
@interface Foo : NSObject 
…// Do something with Bar 
@end

…导入Bar.h(并删除评论…但让我们关注主题。)…

// Foo.h
   // Bar.h
   #import "Foo.h"
   @interface Bar : NSObject 
   …// Do something with Foo 
   @end

@interface Foo : NSObject 
…// Do something with Bar 
@end

Foo.h不会再导入了,因为已经导入了。最后:

   // Bar.h
   @interface Bar : NSObject 
   …// Do something with Foo 
   @end

@interface Foo : NSObject 
…// Do something with Bar 
@end

这就很清楚了:如果A依赖B,B依赖A,那么像文件这样的串行数据流不可能同时有A先于B,B又先于A。 (文件不是相对论的对象。)

乙。解决方案

在大多数情况下,你应该给你的代码一个层次结构。 (出于多种原因。没有进口问题是最不重要的原因之一。)即。在您的代码中,将 SomeClass.h 导入 DataProvider.h 看起来很奇怪。

有这样的问题是代码味。尝试隔离并修复其原因。不要将代码块移动到不同的位置以找到它工作的节奏。这是代码抽奖。

摄氏度。结构

通常你有一个 class 期望其他人遵守协议。让我们举个例子:

// We declare the protocol here, because the class below expects from other classes to conform to the protocol.

@protocol DataSoure
…
@end

@interface Aggregator : NSObject 
- (void)addDataSource:(id<DataSource>)dataSource 
// We are using a protocol, because we do not want to restrict data sources to be subclass of a specific class.
// Therefore in this .h there cannot be an import of that – likely unknown - class
@end

SomeClass,符合协议

#import "Aggregator.h"

@interface SomeClass:NSObject<DataSource>
…
@end