转发在objective-c中声明协议 [英] Forward declaring a protocol in objective-c
问题描述
我的班级.h看起来像:
My class .h looks like:
@protocol AppInfoDelegate;
@class InfoTextView;
@interface AppInfoViewController : UIViewController <AppInfoDelegate> {
}
@property (nonatomic, retain) NSArray *textObjectsArray;
@property (nonatomic, retain) InfoTextView *itView;
@property (nonatomic, retain) UIButton *pgBackButton;
@property (nonatomic, retain) UIButton *pgFwdButton;
@end
@protocol AppInfoDelegate <NSObject>
- (void)closeButtonPressed:(id)sender;
@end
我收到一条警告,说AppInfoDelegate的协议定义不能被发现。这样做的正确方法是什么,为什么不能找到它?我是否需要在接口之前获得协议的完整定义?谢谢!
I get a warning that the protocol definition for AppInfoDelegate cannot be found. What is the proper way to do this and why cannot it not be found? Do I need to have the whole definition of the protocol before the interface? Thanks!
推荐答案
使用 @protocol MyProtocol;
非常有用断言,例如,一个方法将 id< MyProtocol>
作为参数。
Using @protocol MyProtocol;
is useful when you are asserting, for example, that a method will take id <MyProtocol>
as an argument.
它是<当您声称您的班级符合< MyProtocol>
时,em> not 非常有用。原因是编译器需要完整的协议声明才能验证您的类实际是否符合协议。 (这个编译时检查是使用正式协议而不是旧的非正式协议的一个很好的理由。)
It is not useful when you are claiming that your class conforms to <MyProtocol>
. The reason for this is that the compiler needs the full protocol declaration in order to verify that your class actually conforms to the protocol. (This compile-time check is one great reason to use formal protocols instead of the older informal ones.)
您可以通过两种方式修复。正如@skram所暗示的那样,只是向前宣告整个事情。这有效,但在我看来它也相当有限。在这种情况下为什么还要使用协议 - 只需将所有内容放在类 @interface
中,然后完成它。
You can fix in two ways. One, as @skram suggests, is to just forward-declare the whole thing. This works, but it's also rather limited in my view. Why bother with a protocol in that case - just put everything in the class @interface
and be done with it.
我更喜欢的第二种方法是实际上有一个单独的标题,例如 MyProtocol.h
。然后,您可以根据需要随意将其导入任何标头或实现文件。这允许您轻松地重用协议(并避免有时会出现循环导入的麻烦)。
The second approach, which I prefer, is to actually have a separate header, such as MyProtocol.h
. You can then freely import this into any header or implementation files as needed. This allows you to reuse a protocol easily (and avoid the headaches of circular imports that sometimes arise).
这篇关于转发在objective-c中声明协议的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!