无法find协议声明

我有两个对象,都是视图控制器。 第一个(我把它称为viewController1)声明一个协议。 第二个(毫不奇怪,我将命名viewController2)符合这个协议。

XCode给我一个构build错误:'找不到viewController1的协议声明'

我已经看到了这个问题上的各种问题,我确定这是一个循环错误,但我不能看到它在我的情况下…

下面的代码

viewController1.h

@protocol viewController1Delegate; #import "viewController2.h" @interface viewController1 { } @end @protocol viewController1Delegate <NSObject> // Some methods @end 

viewController2.h

 #import "viewController1.h" @interface viewController2 <viewController1Delegate> { } @end 

最初,我在viewController1的协议声明的上面有导入行。 这阻止了这个项目的build设。 在search完成后,我意识到了这个问题,并转换了两条线。 我现在得到一个警告(而不是一个错误)。 该项目build立良好,实际运行完美。 但我仍然觉得一定有什么不对的地方可以给予警告。

现在,就我所知,当编译器到达viewController1.h时,它看到的第一件事就是协议的声明。 然后导入viewController.h文件,并看到这个实现了这个协议。

如果是以相反的方式编译它们,它首先会查看viewController2.h,并且首先会导入viewController1.h,其中第一行是协议声明。

我错过了什么吗?

viewController1.h删除这一行:

 #import "viewController2.h" 

问题是viewController2的接口在协议声明之前被预处理。

该文件的一般结构应该是这样的:

 @protocol viewController1Delegate; @class viewController2; @interface viewController1 @end @protocol viewController1Delegate <NSObject> @end 
  Ah: #import "Bh" // A @class A; @protocol Delegate_A (method....) @end @interface ViewController : A @property(nonatomic,strong)id<ViewControllerDelegate> preViewController_B;(protocol A) @end Bh: #import "Ah" // A @class B; @protocol Delegate_B (method....) @end @interface ViewController : B @property(nonatomic,strong)id<ViewControllerDelegate> preViewController_A;(protocol B) @end Am: @interface A ()<preViewController_B> @end @implementation A (implement protocol....) end Bm: @interface B ()<preViewController_A> @end @implementation B (implement protocol....) @end 

对于那些可能需要它的人:

也可以通过移动ViewController2的实现文件(.m)而不是头文件(.h)来导入ViewController1.h来解决这个问题。

像这样:

ViewController1.h

 #import ViewController2.h @interface ViewController1 : UIViewController <ViewController2Delegate> @end 

ViewController2.h

 @protocol ViewController2Delegate; @interface ViewController2 @end 

ViewController2.m

 #import ViewController2.h #import ViewController1.h @implementation ViewController2 @end 

这将解决发生错误的情况,因为ViewController1.h在协议声明之前在ViewController2.h中被导入。