programmingwithobjectivec学习笔记(五)

本文介绍了Objective-C中的协议概念,包括如何定义和实现协议,可选与必选方法的区别,运行时检查可选方法的实现,协议间的继承关系,以及如何声明类遵循多个协议。此外,还探讨了匿名协议的应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值