Protocol(协议)、Delegate(委托)、DataSource(数据源)

这里以 UITableViewController 和 UITableView 的关系为例:

 

//------------------------------------------------------------------------
// UITableViewController.h
@interface UITableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property(nonatomic,retain) UITableView *tableView;
@end


//------------------------------------------------------------------------
// UITableView.h
@protocol UITableViewDataSource;

@protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
@optional
// Delegate方法都是可选的
@end

@interface UITableView : UIScrollView <NSCoding>
@property (nonatomic, assign)   id <UITableViewDataSource> dataSource;
@property (nonatomic, assign)   id <UITableViewDelegate>   delegate;
@end

@protocol UITableViewDataSource<NSObject>
@required
// 必须实现的DataSource方法
@optional
// 可选的DataSource方法
@end

 

1、UITableViewController 实现了 UITableViewDelegate 和 UITableViewDataSource 两个协议

2、这两个协议是在 UITableView 中定义的

  注意:定义时可以加上<NSObject>,表示同时也实现父协议中的方法

3、协议定义好后,就可以声明两个属性来放置其委托对象:dataSource 和 delegate

  注意:如果协议的定义放在属性声明的后面,那么在前面要提前先声明下协议,如 @protocol UITableViewDataSource;

  上面代码的顺序是完全按照库文件中来的,不知为何 delegate 定义在前,dataSource 定义在后,maybe是展示下两种形式吧(我瞎猜的~)

  注意:这两个属性是assign的,换句话说,是weak非strong,原因是 UITableViewController 有个属性 UITableView(前者拥有后者),而 UITableView 的委托和数据源又指向 UITableViewController,如果设为stong,则会互为拥有,引入 retain cycle(保留环)

4、实现委托对象的方法是声明某个类遵从委托协议,然后把协议中想实现的方法在类里实现

 

posted @ 2015-06-14 23:46  mobilefeng  阅读(366)  评论(0编辑  收藏  举报