[英]Cannot find protocol declaration for
我有兩個對象,它們都是視圖控制器。 第一個(我稱之為viewController1)聲明了一個協議。 第二個(毫無疑問,我將其命名為viewController2)符合此協議。
XCode給我一個構建錯誤:'找不到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中的導入行位於協議聲明的上方。 這根本阻止了該項目的建設。 在搜索SO之后,我意識到了問題,並切換了兩行。 我現在收到警告(而不是錯誤)。 該項目構建良好,並且實際上運行良好。 但是我仍然覺得必須有一些錯誤才能給予警告。
現在,據我所知,當編譯器進入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
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
對於可能需要的人:
也可以通過在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中的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.