找不到协议声明

27
我有两个对象,都是视图控制器。第一个对象(我称其为 viewController1)声明了一个协议。第二个对象(不出所料,我会将其命名为viewController2)符合此协议。
XCode 给出了一个构建错误:'Cannot find protocol declaration for 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

一开始,我把import语句放在viewController1中protocol声明之前。这完全阻止了项目的构建。在Stack Overflow上搜索后,我意识到了问题所在,并交换了两个行的位置。现在我收到一个警告(而不是一个错误)。该项目构建得很好,实际上运行得非常完美。但我仍然觉得会有一些问题,才会收到警告。

据我所见,当编译器到达viewController1.h时,它首先看到的是协议的声明。然后导入viewController.h文件并查看是否实现了此协议。

如果以相反的顺序编译它们,它将首先查看viewController2.h,然后第一件事是导入viewController1.h,其中第一行是协议声明。

我有什么遗漏吗?

3个回答

68

viewController1.h 中删除此行:

#import "viewController2.h"

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

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

@protocol viewController1Delegate;
@class viewController2;

@interface viewController1
@end

@protocol viewController1Delegate <NSObject>
@end

1
我应该说,viewController1确实需要能够呈现viewController2。我不能...(我应该已经这么说了)... - Ben Thompson
2
有一个 @class viewController2; 指令可以实现这个。在 viewController1.m 中导入头文件。 - Costique

1

对于可能需要的人:

也可以通过将ViewController1.h的导入移到ViewController2的实现文件(.m)中来修复此问题,而不是在头文件(.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

这将修复错误发生的情况,因为在协议声明之前在ViewController2.h中导入了ViewController1.h

1
    A.h:
    #import "B.h"  // A

    @class A;

    @protocol Delegate_A 
       (method....)
    @end

    @interface ViewController : A
    @property(nonatomic,strong)id<ViewControllerDelegate> preViewController_B;(protocol A)
    @end


    B.h:
    #import "A.h"  // A

    @class B;

    @protocol Delegate_B 
       (method....)
    @end

    @interface ViewController : B
    @property(nonatomic,strong)id<ViewControllerDelegate> preViewController_A;(protocol B)
    @end

    A.m:
    @interface A ()<preViewController_B>
    @end

    @implementation A
    (implement protocol....)
    end


    B.m:
    @interface B ()<preViewController_A>
    @end

    @implementation B
    (implement protocol....)
   @end

你能添加一些注释或细节吗?这将提高你的回答质量并更好地教育每个人。 - NonCreature0714

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接