2016年2月14日 星期日

iOS筆記:Protocols and Delegation

Protocol 跟 Delegate

你需要做一件事情,你自己不想動手,委託給 delegate 處理,為了避免所託非人,delegate 需要遵守一個你和 delegate 都能接受的 protocol。一個類只要聲明它遵守了某個你想要的 protocol,你就能把它信認為是你的 delegate。

如果使用Apple的delegate是什麼情況?

  1. 在h檔引用適當的protocol。
  2. 依照引用的protocol,於m檔實作必須的方法。
  3. 於m檔加入類似:self.delegate=self的程式碼。

若是要一個delegate method完成值的傳遞必須具備以下內容:

  1. 一個protocol定義檔。
  2. 一個delegate method的執行或運算邏輯。
  3. 一個引用上述protocol,並實作完成的程式檔。

Protocol 範例:
如果沒特別標明的,預設是@required

@protocol Drawable

@required
-(void) draw;

@optional
-(void) whateverMethod;

@end

Delegate 自己動手樂趣多

以下範例為我們想從B傳資料到C, 但是在C視窗中使用back button我們想回到A.

所以在這邊就是要使用Delegate 讓B傳訊息給A, 再讓A去投射到C.
enter image description here

delegate 使用的前三步(委託者):
1. 宣告 delegate 原型
2. 宣告 delegate 變量
3. 調用 delegate 方法

先在B視窗內宣告Protocol:

//B視窗.h file
@protocol PFMatchViewControllerDelegate
-(void)presentMatchesViewController;
@end

@interface PFMatchViewController : UIViewController
@property (weak) id <PFMatchViewControllerDelegate> delegate;
...
@end
//B視窗.m file
- (IBAction)viewChatsButtonPressed:(UIButton *)sender
{
    [self.delegate presentMatchesViewController];
}

delegate 使用的後三步(被委託者):
4. 宣告實現 delegate
5. 設置 delegate 的值
6. 實現 delegate 方法

A視窗.m file

#import "B視窗.h"

@interface PFHomeViewController () <PFMatchViewControllerDelegate>
...
@end

@implementation A視窗
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    BViewController *matchVC = segue.destinationViewController;
    matchVC.delegate = self;
}

- (void)presentMatchesViewController
{
    [self dismissViewControllerAnimated:NO completion:^{
        [self performSegueWithIdentifier:@"homeToMatchesSegue" sender:nil];
    }];
}
@end

matchVC.delegate = self這句話的涵義:
將實作B delegate的A View(self), 指派給B的Delegate屬性中, 好將B視窗取得資料的工作, 委派給A View(self)物件。

Note

  1. 因為Obj-C是不支持多繼承的,所以很多時候都是用Protocol來代替.
  2. delegate 這個 property 並不一定要命名為 delegate,只是慣例上通常會使用 delegate 這個名字
  3. protocol 的定義也不一定要放在同一個 header 檔裡,也可以另外獨立的檔案, 但通常都會寫在同一個檔案裡
  4. protocol 本身不會實作,只會宣告 method,實作的部分由使用這個 protocol 的 class 來實作.

參考:
1. http://www.jianshu.com/p/2310f29d45e0s
2. http://lokanghung.blogspot.tw/2013/06/ios-delegate-protocol.html
3. http://blog.eddie.com.tw/2013/05/24/delegation-in-objective-c/
4. http://www.cnblogs.com/GarveyCalvin/p/4210828.html

沒有留言:

張貼留言