Understanding multiple mentions of delegate protocol in sample code
I got this code from one of Apple's examples:
@protocol SectionHeaderViewDelegate;
@inte开发者_高级运维rface 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 protocol
declaration 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 do id<SectionHeaderViewDelegate> delegate
in the SectionHeaderView
class. The next @protocol
declaration is to signal the actual start of the protocol definition.
The first @protocol
is a forward declaration of the protocol. It's of the form @protocol SuchAndSuch;
— note the semicolon — and it just tells the compiler "There's a protocol with this name, so allow the name to be used wherever a protocol is expected".
The second time, after the comment, is when the protocol is actually defined. That time, it's of the form @protocol SuchAndSuch … @end
.
The first @protocol SectionHeaderViewDelegate tells the class that there is a protocol with this name (to avoir compilation error)
The 4th property, delegate means that there is attribute named "delegate" that can be of any Class (id) and that implements the protocol "SectionHeaderViewDelegate"
And in the end of the file, the protocol is defined with methods to imeplent
精彩评论