I got this code from one of Apple’s examples:
@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
I’m confused on some of the notation. This is my attempt at explaining it. Please correct me if I’m wrong:
The first @protocol SectionHeaderViewDelegate; declares the start of the protocol for the SectionHeaderView class. The fourth property, id <SectionHeaderViewDelegate> delegate; is needed for classes that conform to the protocol so they can do something like instanceOfClass.delegate = self;.
Then after the /* comment */, I’m not sure why the protocol directive is used again. Is it part of the same protocol? Is it different than the protocol declared in the first half?
Is my above explanation and understanding of the code correct?
Actually the first
protocoldeclaration is forward declaration to solve a chicken and egg problem. Both the delegator class the delegate protocol need to know about each other so to solve this we declare@protocol SectionHeaderViewDelegate;as a forward declaration saying that it’s not defined yet but it will be there and you needn’t worry about it. This works when you doid<SectionHeaderViewDelegate> delegatein theSectionHeaderViewclass. The next@protocoldeclaration is to signal the actual start of the protocol definition.