2012-04-15 258 views
25

我有两个对象,它们都是视图控制器。第一个(我称之为viewController1)声明一个协议。第二个(我不会惊讶地命名viewController2)符合这个协议。找不到协议声明

Xcode是给我的生成错误:“无法找到viewController1协议声明”

我已经看到了关于这个问题的各种问题,我敢肯定这是一个循环的错误的事,但我就是“T看到它在我的情况...以下

代码..

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导入行。这阻止了该项目的建设。在搜索结果后,我意识到了这个问题,并转换了两条线。我现在得到一个警告(而不是一个错误)。该项目建立良好,实际运行完美。但我仍然觉得必须有什么错误才能给予警告。

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

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

我错过了什么吗?

回答

67

viewController1.h删除此行:

#import "viewController2.h" 

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

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

@protocol viewController1Delegate; 
@class viewController2; 

@interface viewController1 
@end 

@protocol viewController1Delegate <NSObject> 
@end 
+1

我不能......(我应该说)... viewController1确实需要能够呈现一个viewController2。 – 2012-04-15 09:39:16

+2

这里有'@class viewController2;'指令。在'viewController1.m'中导入头文件。 – Costique 2012-04-15 09:41:01

+1

我更新了答案来说明这一点。 – Costique 2012-04-15 09:44:23

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 
+0

你可以添加一些评论或细节?它会提高你答案的质量,并更好地教育每个人。 – NonCreature0714 2016-07-15 03:50:41

1

对于那些谁可能需要它:

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

像这样:

ViewController1.h

#import ViewController2.h 

@interface ViewController1 : UIViewController <ViewController2Delegate> 
@end 

ViewController2.h

@protocol ViewController2Delegate; 

@interface ViewController2 
@end 

ViewController2。米

#import ViewController2.h 
#import ViewController1.h 

@implementation ViewController2 
@end 

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

相关问题