协议是对象行为的抽象,定义了消息合约。Objective-C中可以实现多个协议
@protocol XYZPieChartViewDataSource - (NSUInteger)numberOfSegments; - (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex; @optional - (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex; - (BOOL)shouldExplodeSegmentAtIndex:(NSUInteger)segmentIndex; @required - (UIColor *)colorForSegmentAtIndex:(NSUInteger)segmentIndex; @end
@optional的实现是可选的,@required的实现则是必须的。
实现多协议
@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol> ... @end
id类型的协议约束
由于id类型是范型,编译器无法在编译阶段对其类型进行检查,但提供了对其协议约束的语法
id <XYZFrameworkUtility> utility = [frameworkObject anonymousUtility];
这样,编译器就会检查utility是否实现了XYZFrameworkUtility协议。