• 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、实现委托对象的方法是声明某个类遵从委托协议,然后把协议中想实现的方法在类里实现

  • 相关阅读:
    JS给数字加千位分隔符
    前端防抖与节流实现与应用
    JS实现单向链表、双向链表、循环链表
    单点登录
    AMD、CMD规范
    JS实现全排列
    event loop、进程和线程、任务队列
    BOM属性对象方法
    JS的闭包、高阶函数、柯里化
    for...in、for...of、forEach()有什么区别
  • 原文地址:https://www.cnblogs.com/mobilefeng/p/4576022.html
Copyright © 2020-2023  润新知