Working with Protocols (协议)
Protocols Define Messaging Contracts
一个class的interface声明了方法和属性与该类关联。一个protocols,也是用来声明方法和属性,但是不同的是,他是独立于任何特定的class的。
实例可以声明属性,类方法,实例方法
@protocol ProtocolName
// list of methods and properties
@end
//定义协议如下
@protocol XYZPieChartViewDataSource
- (NSUInteger)numberOfSegments;
- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
@end
@interface XYZPieChartView : UIView
@property (weak) id <XYZPieChartViewDataSource> dataSource;
...
@end
Protocols Can Have Optional Methods
协议也可以有方法,如下用@optional(可选实现)和@require(必选实现)
@protocol XYZPieChartViewDataSource - (NSUInteger)numberOfSegments; - (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex; @optional//可选实现 - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex; - (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex; @required//必选实现 - (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex; @end
Check that Optional Methods Are Implemented at Runtime
NSString *thisSegmentTitle;
if ([self.dataSource respondsToSelector:@selector(titleForSegmentAtIndex:)] {
thisSegmentTitle = [self.dataSource titleForSegmentAtIndex:index];
}
如上用respondsToSelector判断函数判断函数是否实现(获取方法实现后的标示符),如果实现了返回used,未实现则返回一个nil
Protocols Inherit from Other Protocols
@protocol MyProtocol <NSObject>
...
@end
Conforming to Protocols
@interface MyClass : NSObject <MyProtocol>
...
@end
符合多个协议,如下
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
...
@end
Protocols Are Used for Anonymity
id <XYZFrameworkUtility> utility = [frameworkObject anonymousUtility];
原始类没有符合XYZFrameworkUtility协议,但是其实例符合了XYZFrameworkUtility协议,此协议只在该实例中符合,是匿名的。
Protocols Are Used for Anonymity