programmingwithobjectivec学习笔记(五)

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 

如果方法被标记为@optional(可选实现),那么需要在调用前判断其是否已被实现

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
这说明所有MyClass的实例都拥有MyClass和协议MyProtocol的所有方法和属性

符合多个协议,如下

@interface MyClass : NSObject <MyProtocol, AnotherProtocol, YetAnotherProtocol>
...
@end

Protocols Are Used for Anonymity 

匿名的协议用法

id <XYZFrameworkUtility> utility = [frameworkObject anonymousUtility];
???????????????????????????????????????

原始类没有符合XYZFrameworkUtility协议,但是其实例符合了XYZFrameworkUtility协议,此协议只在该实例中符合,是匿名的。

Protocols Are Used for Anonymity 

你可能感兴趣的:(programmingwithobjectivec学习笔记(五))