[英]Forward declaring a protocol in objective-c
我的课.h看起来像:
@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的协议定义。 正确的方法是什么?为什么找不到它? 接口之前是否需要对协议进行完整定义? 谢谢!
使用@protocol MyProtocol;
例如,当您断言某个方法将以id <MyProtocol>
作为参数时,此id <MyProtocol>
用。
当您声称自己的类符合<MyProtocol>
时,它没有用。 这样做的原因是,编译器需要完整的协议声明,以验证您的类确实符合该协议。 (此编译时检查是使用正式协议而不是较早的非正式协议的重要原因。)
您可以通过两种方式进行修复。 正如@skram所建议的,只是向前声明整个事情。 这可行,但在我看来也相当有限。 在这种情况下,为什么要麻烦协议-只需将所有内容放在@interface
类中并使用它即可。
我更喜欢的第二种方法是实际上有一个单独的头,例如MyProtocol.h
。 然后,您可以根据需要将其随意导入任何头文件或实现文件中。 这使您可以轻松地重用协议(并避免有时会引起循环导入的麻烦)。
尝试这个:
@protocol AppInfoDelegate <NSObject>
- (void)closeButtonPressed:(id)sender;
@end
@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
是的,需要在类定义之前定义超类和采用的协议定义(普通或通过使用#import)。 它们不能被预先声明。
我一直在@interface之前看到过整个协议定义。 我相信您也可以将其放入单独的文件中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.