Iphone 在objective-c中向前声明协议
我的类.h看起来像:Iphone 在objective-c中向前声明协议,iphone,objective-c,Iphone,Objective C,我的类.h看起来像: @protocol AppInfoDelegate; @class InfoTextView; @interface AppInfoViewController : UIViewController <AppInfoDelegate> { } @property (nonatomic, retain) NSArray *textObjectsArray; @property (nonatomic, retain) InfoTextView *itVie
@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
@protocol-AppInfoDelegate;
@类InfoTextView;
@接口AppInfoViewController:UIViewController{
}
@属性(非原子,保留)NSArray*textObjectsArray;
@属性(非原子,保留)InfoTextView*itView;
@属性(非原子,保留)UIButton*pgBackButton;
@属性(非原子,保留)UIButton*pgFwdButton;
@结束
@协议AppInfoDelegate
-(无效)关闭按钮按下:(id)发件人;
@结束
我收到一条警告,无法找到AppInfoDelegate的协议定义。正确的方法是什么?为什么找不到?在接口之前,我需要完整定义协议吗?谢谢 我总是在@interface之前看到整个协议定义。我相信你也可以把它放在一个单独的文件中,不过试试这个:
@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
@协议AppInfoDelegate
-(无效)关闭按钮按下:(id)发件人;
@结束
@类InfoTextView;
@接口AppInfoViewController:UIViewController{
}
@属性(非原子,保留)NSArray*textObjectsArray;
@属性(非原子,保留)InfoTextView*itView;
@属性(非原子,保留)UIButton*pgBackButton;
@属性(非原子,保留)UIButton*pgFwdButton;
@结束
是的,在类定义之前需要定义超类和采用的协议定义(逐字或使用#导入)。它们不能被转发声明。使用@protocol-MyProtocol例如,当您断言一个方法将id
作为参数时,code>非常有用
当您声明您的类符合
时,它没有用处。这样做的原因是编译器需要完整的协议声明,以便验证您的类是否确实符合协议。(这种编译时检查是使用正式协议而不是旧的非正式协议的一个重要原因。)
您可以通过两种方式进行修复。正如@skram所建议的,其中之一就是向前宣布整个事件。这是可行的,但在我看来也是相当有限的。在这种情况下,为什么还要麻烦协议呢?只要把所有的东西都放在类@接口中
就可以了
第二种方法,我更喜欢,实际上是有一个单独的头,比如MyProtocol.h
。然后,您可以根据需要将其自由导入任何头文件或实现文件。这使您可以轻松地重用协议(并避免有时出现的循环导入带来的麻烦)