了解示例代码中的多个委托协议

Cry*_*tal 3 cocoa-touch delegates protocols objective-c ios

我从Apple的一个例子中得到了这段代码:

@protocol SectionHeaderViewDelegate;


@interface SectionHeaderView : UIView {
}

@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UIButton *disclosureButton;
@property (nonatomic, assign) NSInteger section;
@property (nonatomic, assign) id <SectionHeaderViewDelegate> delegate;

-(id)initWithFrame:(CGRect)frame title:(NSString*)title section:(NSInteger)sectionNumber delegate:(id <SectionHeaderViewDelegate>)aDelegate;
-(void)toggleOpenWithUserAction:(BOOL)userAction;

@end



/*
 Protocol to be adopted by the section header's delegate; the section header tells its delegate when the section should be opened and closed.
 */
@protocol SectionHeaderViewDelegate <NSObject>

@optional
-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionOpened:(NSInteger)section;
-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionClosed:(NSInteger)section;

@end
Run Code Online (Sandbox Code Playgroud)

我对某些符号感到困惑.这是我试图解释它. 如果我错了,请纠正我:

第一个@protocol SectionHeaderViewDelegate;声明了SectionHeaderView类的协议的开始.id <SectionHeaderViewDelegate> delegate;对于符合协议的类,需要第四个属性,以便它们可以执行类似的操作instanceOfClass.delegate = self;.

然后/* comment */,我不知道为什么再次使用协议指令.它是同一协议的一部分吗?它与上半年宣布的协议不同吗?

我的上述解释和对代码的理解是否正确?

Dee*_*olu 6

实际上,第一个protocol声明是解决鸡和蛋问题的前瞻性声明.代理协议需要知道彼此的委托者类,所以为了解决这个问题,我们声明它@protocol SectionHeaderViewDelegate;是一个前向声明,说它还没有定义,但它会存在,你不必担心它.当你做这个工作id<SectionHeaderViewDelegate> delegateSectionHeaderView类.下一个@protocol声明是表示协议定义的实际开始.