您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 開發:用 protocol 與 delegate 在兩個畫面間傳值

編輯:iOS 開發綜合

剛接觸 iOS 開發時,常會困惑於兩個 UIViewController 之間如何傳值。其中一種典型做法是使用 protocol 定義回傳介面,再以 delegate 讓呼叫方接收資料。

protocol 的角色

protocol 是一組方法宣告。遵循該 protocol 的類別,必須實作其中必要的方法。它常用來定義「事件發生後,應該由誰來處理」的規則。

delegate 的角色

delegate 是一種設計模式,意思是把部分工作委託給另一個物件處理。在兩個畫面之間,通常會由被叫出的畫面定義 protocol,再由叫出它的畫面作為 delegate 接收結果。

定義回傳介面

在第二個 view controller 中,可宣告一個 protocol,用來回傳輸入值。

@protocol WTwoViewControllerDelegate
- (void)changeValue:(NSString *)value;
@end

接著在第二個 view controller 中宣告 delegate 屬性,並在按下按鈕時觸發代理方法。

@property (nonatomic, unsafe_unretained) id delegate;

- (IBAction)pressChange:(id)sender {
    [self.delegate changeValue:self.txtValue.text];
    [self dismissViewControllerAnimated:YES completion:nil];
}

第一個畫面接收資料

第一個 view controller 在叫出第二個畫面前,先把 delegate 設為自己,並實作 protocol 方法。

WTwoViewController *controller = [[WTwoViewController alloc] initWithNibName:@"WTwoViewController" bundle:nil];
controller.delegate = self;
[self presentViewController:controller animated:YES completion:nil];

- (void)changeValue:(NSString *)value {
    self.lblValue.text = value;
}

重點整理

這種做法讓資料流更清楚:第二個畫面只負責產生結果並透過 delegate 回傳,第一個畫面則決定收到資料後要做什麼。若未來需要擴充更多回傳事件,也可在 protocol 中新增方法。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved