代理模式的定义:为其他对象提供一种代理以控制对这个对象的访问。在某些情况下,一个对象不适合或者不能直接引用另一个对象,而代理对象可以在客户端和目标对象之间起到中介的作用。
就拿UITableView举例子.一般我们把数据源方法、代理方法设置到UIViewController里头.这是因为UIViewController无法直接控制UITableView这个对象的访问.将UIViewController设置为UITableView的代理.就能起到中介作用就可以使用UITableView的一些代理方法了.
1.创建协议,并且声明协议方法
@protocol UITableViewDataSource<NSObject>
//必选方法
@required
xxx
//可选方法
@optional
xxx
2.声明委托变量
@property (nonatomic, weak, nullable) id <UITableViewDataSource> dataSource;
3.遵守代理
@interface ViewController () <UITableViewDataSource>
@end
4.设置代理
- (void)viewDidLoad {
[super viewDidLoad];
self.tableView.dataSource = self;
}
5.使用委托变量来调用相应方法.
1. 猜测UITableView里头怎么实现的
///下面是UITableView中的猜测,毕竟看不到源码
@implementation UITableView
- (void)xxx {
if ([self.delegate isResponseToSelector:@selector(tableView: numberOfRowsInSection:]) {
[self.delegate tableView:self numberOfRowsInSection:(NSInteger)section];
}
}
@end
6.实现协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return xxx;
}