在 iOS 開發中,界面之間傳遞訊息或數據是最基本的一種需求。我們可以用很多方法來實現,例如在標頭檔中暴露一個屬性、使用 notification 等等。今天我們要介紹另一種方式:使用 delegate 傳遞訊息。
delegate 稱為委託,同時也是一種代理設計模式。使用委託能避免類與類之間的耦合度過高,而且透過委託賦值更加安全可控——委託賦值能在不暴露自身類別屬性的前提下,對自己進行賦值。
在 iOS 中,委託是透過協議 @protocol 來實現的。協議中所宣告的方法,並不需要在協議內部有實作,而是由它的實作類來完成(該類需要在標頭檔中包含 <協議名>)。「協議」與「委託」其實是兩個不同的概念,只是我們在看程式碼時總會看到它們一起出現。但不能因此就說 delegate 就是 protocol——delegate 是一種架構模式。舉個例子說明什麼是「委託」:比如我正在開車,開車時不能看簡訊,於是我請車裡的朋友幫我看簡訊,這樣我就能安心開車了;當朋友看完簡訊內容後,就把內容告訴我。這就是委託,朋友就是我的委託對象。而「協議」protocol 是用來定義物件的屬性與行為,類似於 C++ 中的虛函式,其中有兩個關鍵字 @required 與 @optional,前者表示必須要實作的方法,後者則是可選的方法。
使用 delegate 常用在兩種情況:
*兩個類之間傳值:類 A 呼叫類 B 的方法,類 B 在執行過程中遇到問題時通知類 A;
*控制器(ViewController)與控制器之間傳值:從 A 跳轉到 B,再從 B 返回 A 時需要通知 A 更新 UI 或做其他事情,這時就用到了代理(delegate)傳值。
tips:如果沒有在 @protocol 中明確寫上 @required 或 @optional,那麼預設就是 @required(必需的)。為避免歧義,最好明確寫上 @required 或 @optional。
通常一個 delegate 的使用過程需要經過 5 步:
(1)建立一個 delegate;
(2)委託者宣告一個 delegate;
(3)委託者呼叫 delegate 內的方法(method);
(4)被委託者設定 delegate,以便被委託者呼叫;
(5)被委託者實作 delegate 所定義的方法。
下面我透過 1 個實例來演示使用 delegate 傳遞數據,程式碼已上傳至:https://github.com/chenyufeng1991/iOS-Delegate 中的 Delegate01。
(1)首先,程式是基於 storyboard 來建構的,界面布局如下:在界面返回時將會傳遞數據。

(2)新增一個 Protocol,作為我們的協議,裡面可以宣告一些方法。如下圖:

ProtocolDelegate 裡面的實作如下:
#import//實現一個protocol; /** * 可以理解為Java中的接口interface; */ @protocol ProtocolDelegate // 必須實現的方法 @required - (void)execute; // 可選實現的方法 @optional - (void)function1; - (void)function2; - (void)function3; @end
(3)我先來實作第二個界面。在第二個界面的標頭檔 .h 中需要宣告一個 protocol,在該 protocol 中宣告的方法可以在第一個界面中實作,並在第二個界面中進行呼叫——這是數據傳遞的關鍵。
#import// 新建一個協議,協議的名字一般是由“類名+Delegate” /** * 在該協議中聲明的方法,在第一個界面中實現,在該界面中調用; */ @protocol ViewControllerBDelegate @required - (void)sendValue:(NSString *)value; @end @interface ViewControllerB : UIViewController //這裡的delegate要設置在.h中; @property (weak, nonatomic) id delegate; @end
(4)在第二個界面的實作檔中實作如下:在點擊返回鍵時呼叫協議中的方法。
#import "ViewControllerB.h" //第二個界面; @interface ViewControllerB () @property (strong, nonatomic) IBOutlet UITextField *textField; @end @implementation ViewControllerB - (IBAction)backAction:(id)sender{ //界面跳轉的時候調用該方法; [self.delegate sendValue:self.textField.text]; // 通知執行協議方法 //返回傳遞消息; [self.navigationController popViewControllerAnimated:YES]; } @end
(5)下面來實作第一個界面 ViewController.m:
#import "ViewController.h" #import "ProtocolDelegate.h" #import "ViewControllerB.h" //第一個界面; @interface ViewController ()@end @implementation ViewController //因為是基於storyboard的segue來構建,當界面跳轉時,自動回調該方法; - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ ViewControllerB *vc = segue.destinationViewController; [vc setDelegate:self]; } // 這裡實現B控制器的協議方法 - (void)sendValue:(NSString *)value{ UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功" message:value delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil, nil]; [alertView show]; } //該方法是ProtocolDelegate中的@required方法; - (void)execute{ } - (IBAction)pressed:(id)sender { NSLog(@"1111"); } @end
(6)執行效果如下:


上面的 demo 是基於 storyboard。由於有些專案是基於 nib 檔建構的,我下面來演示一下使用 nib 檔時的注意事項。
(1)刪除原來的 main.storyboard,新增兩個 nib 檔,分別綁定對應的 ViewController。我推薦使用 navigationBar,所以在 AppDelegate.m 中的實作如下:
#import "AppDelegate.h" #import "ViewController.h" @interface AppDelegate () @end @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; self.window.rootViewController = [[ViewController alloc] init]; self.naviController = [[UINavigationController alloc] initWithRootViewController:self.window.rootViewController]; [self.window addSubview:self.naviController.view]; [self.window makeKeyAndVisible]; return YES; } @end
(2)在第二個界面中主要修改如下:刪除 prepareForSegue 方法,改在按鈕的點擊方法中實作:
- (IBAction)pressed:(id)sender { //如果項目本身是根據nib文件構建的,就使用下面的方式綁定delegate,並跳轉; ViewControllerB *vb = [[ViewControllerB alloc] initWithNibName:@"ViewControllerB" bundle:[NSBundle mainBundle]]; vb.delegate = self; [self.navigationController pushViewController:vb animated:true]; }
然後執行效果同上,不同之處只在於 ViewController 綁定 delegate 的地方有所差異。
總結來說,Delegate 委託屬於程式架構層面,是相對比較高層次的東西。如果我們能夠熟練使用 delegate,就能有效降低程式耦合度、提高程式碼可讀性!