Protocol(协议)、Delegate(委托)、DataSource(数据源)
2015-06-14 23:46
525 查看
这里以 UITableViewController 和 UITableView 的关系为例:
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、实现委托对象的方法是声明某个类遵从委托协议,然后把协议中想实现的方法在类里实现
//------------------------------------------------------------------------ // 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、实现委托对象的方法是声明某个类遵从委托协议,然后把协议中想实现的方法在类里实现
相关文章推荐
- Effective C++ 条款01解读: 视C++为一个语言联邦
- 线程安全
- HDU4508:湫系列故事——减肥记I(完全背包)
- 《梦断代码》阅读笔记三
- 吊炸天的 PHP 7 ,你值得拥有
- CAN总线移植
- 架构师的路
- poj3934解题报告
- Android进阶篇之引导页系列之ViewPager实现Animation动画引导页
- 准备戒烟了
- iOS:KVO/KVC 的概述与使用
- Android 设置Wifi热点、打开与关闭的监听
- Eclipse出现“The Eclipse executable launcher was unable to locate its companion shared library”错误
- 一起学习CC3200系列教程之TCP ECHO 服务端 selcet
- Spring Data for Mongo 介绍
- hdu1171解题报告
- jlh吃水果
- SpringMVC通过Redis实现缓存主页
- c语言的冒泡排序
- Vim技巧之重复