Objective-C 不支援多重繼承,因此絕大多數需要「共享介面」的場合都以 Protocol(協議)取代。協議只定義一套對外接口,不提供任何實作——它只說明「要做什麼」,不關心「怎麼做」。
當一個類別宣告遵守某個協議,就等於做出承諾。若其中標記為 @required 的方法沒有實作,編譯器會發出警告。注意那是**警告而非錯誤**:即使不實作,程式一樣能跑,只是行為可能不如預期。
用途一:定義一套公用接口
· @required:必須實作的方法
· @optional:可選實作,一個都不寫也合法
用途二:委托代理(Delegate)傳值
Delegate 本身是一個設計模式,語意是「委託別人去做某件事」。典型場景有兩個:
· 類別 A 呼叫類別 B 的方法,B 執行途中遇到狀況需要通知 A;
· 從控制器 C1 跳轉到 C2,C2 返回時需要通知 C1 更新 UI——這就是最常見的「回傳值」場景。
// ProtocolDelegate.h(協議不會產生 .m 檔) #import <Foundation/Foundation.h> @protocol ProtocolDelegate <NSObject> @required - (void)error; @optional - (void)other; - (void)other2; - (void)other3; @end
在使用方引入頭文件並宣告遵守:
#import "ViewController.h" #import "ProtocolDelegate.h" @interface ViewController () <ProtocolDelegate> @end
此時編譯器會警告有 required 方法未實作。補上之後警告消失:
- (void)error {
NSLog(@"錯誤發生");
}
第一步:在 B 中定義自己的協議並宣告 delegate 屬性。命名慣例是「類別名 + Delegate」:
// ViewControllerB.h #import <UIKit/UIKit.h> @protocol ViewControllerBDelegate <NSObject> - (void)sendValue:(NSString *)value; @end @interface ViewControllerB : UIViewController // 代理必須使用 weak,避免循環參照 @property (weak, nonatomic) id<ViewControllerBDelegate> delegate; @end
第二步:A 在跳轉前把自己設為 B 的 delegate。
// ViewController.m
#import "ViewController.h"
#import "ProtocolDelegate.h"
#import "ViewControllerB.h"
@interface ViewController () <ProtocolDelegate, ViewControllerBDelegate>
@end
@implementation ViewController
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
ViewControllerB *vc = segue.destinationViewController;
[vc setDelegate:self];
}
#pragma mark - ViewControllerBDelegate
- (void)sendValue:(NSString *)value {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"成功"
message:value
delegate:nil
cancelButtonTitle:@"確定"
otherButtonTitles:nil];
[alertView show];
}
#pragma mark - ProtocolDelegate
- (void)error {
}
@end
第三步:B 在需要時透過 delegate 回傳。呼叫前先檢查對方是否實作了該方法,這是 optional 方法的標準防護寫法:
// ViewControllerB.m
@interface ViewControllerB ()
@property (strong, nonatomic) IBOutlet UITextField *textField;
@end
@implementation ViewControllerB
- (IBAction)backAction:(id)sender {
if ([_delegate respondsToSelector:@selector(sendValue:)]) {
[_delegate sendValue:_textField.text];
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
1. delegate 一定要用 weak。B 持有 A、A 又持有 B(透過 navigation stack),若 delegate 是 strong 就會形成循環參照,兩者永遠無法釋放。這是最常見的記憶體洩漏來源。
2. 呼叫 optional 方法前用 respondsToSelector: 檢查。少了這個判斷,當對方沒實作時會直接崩潰。
3. 一個協議最好只負責一件事。若協議裡塞了十幾個方法,代表職責過度集中,應考慮拆分為多個小協議。
4. 單向 vs 雙向。若 A 與 B 互相持有對方的 delegate,資料流會變得難以追蹤。此時改用單一資料來源(例如共用 Model 或通知中心)往往更清楚。
5. 現代替代方案。對於「回傳一個值」這種簡單需求,Swift 中常以 closure 取代 delegate,程式碼更集中;但 delegate 在多對一、需要多個回呼方法的場景(如 UITableViewDelegate)仍然是首選,理解它的運作方式依然必要。
需要定義一套公用接口、且各實作方的行為可能不同時,使用 Protocol;需要在類別之間雙向傳值時,基於 Protocol 搭配 Delegate 設計模式。這兩者是 iOS 元件互動的基礎,UIKit 的 UITableView、UITextField 無一例外。