1. 程式人生 > >四.代理設計模式

四.代理設計模式

代理模式的定義:為其他物件提供一種代理以控制對這個物件的訪問。在某些情況下,一個物件不適合或者不能直接引用另一個物件,而代理物件可以在客戶端和目標物件之間起到中介的作用。

就拿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;
    }