iOS 的頁面之間要雙向溝通,委派是最經典的方式。場景很常見:A 頁面彈出一個浮層 B,使用者在 B 裡做了某個選擇,A 需要知道並據此動作。
先打了個比方幫助理解:如果沒有設定代理,就像你沒委託我替你辦事,我跑到銀行或公所去,人家當然不理你。委派本質上就是一份授權書——A 說「你(B)完成之後回報給我」,並把自己登記為可回報的對象。
PopViewController.h:
#import <UIKit/UIKit.h> // 定義回報協定 @protocol PopNextDelegate <NSObject> - (void)passPopReport:(NSString *)string; @end @interface PopViewController : UIViewController // 宣告一個 delegate 屬性,型別為「實作上述協定的物件」 @property (nonatomic, assign) id <PopNextDelegate> delegate; - (IBAction)reportAction:(UIButton *)sender; @end
這裡有個關鍵細節:屬性型別應該寫成 id <PopNextDelegate>,而不是 NSObject <PopNextDelegate> *。前者表示「任何實作了這個協定的物件」,編譯器才會檢查方法是否存在。另外 delegate 應使用 assign / weak,避免循環引用。
PopViewController.m:
- (IBAction)reportAction:(UIButton *)sender
{
// 把資料丟回給 delegate
[self.delegate passPopReport:@"舉報"];
}
ShowViewController.h:
#import "PopViewController.h"
@interface ShowViewController : UIViewController
<iCarouselDataSource, iCarouselDelegate,
UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate,
PopNextDelegate>
{
UIView *moreView;
}
@end
在協定清單中加上 PopNextDelegate,編譯器便會要求你實作其中的方法。
ShowViewController.m:
// 收到 B 的回報
- (void)passPopReport:(NSString *)string
{
if ([string isEqualToString:@"舉報"]) {
ReportViewController *report = [[ReportViewController alloc] init];
[self.navigationController pushViewController:report animated:YES];
}
}
這是最後一塊拼圖,也是最常被遺漏的一步——沒有指定,B 的 self.delegate 就是 nil,回報訊息會石沉大海。
- (void)pop:(id)sender
{
PopViewController *pop = [[PopViewController alloc] init];
pop.delegate = self; // 誰實作了 delegate 方法,就指定給誰
FPPopoverController *basePop =
[[FPPopoverController alloc] initWithViewController:pop];
basePop.tint = FPPopoverLightGrayTint;
basePop.arrowDirection = FPPopoverArrowDirectionAny;
[basePop presentPopoverFromView:sender];
}
b.delegate。[self.delegate 協定方法],資料回流到 A。呼叫 delegate 前先檢查是否實作,可以避免 doesNotRecognizeSelector 崩潰:
if ([self.delegate respondsToSelector:@selector(passPopReport:)]) {
[self.delegate passPopReport:@"舉報"];
}
若把協定方法標為 @optional,這個檢查就是必要的;標為 @required 時雖有編譯期把關,但 runtime 加上判斷仍是更保險的習慣。
委派的最大好處是低耦合:B 完全不需要知道 A 是什麼類別、也不需要 import A 的標頭檔,只認協定。這讓同一個 B 可以被任何数量的頁面複用。若只需要回傳單一值,block 也是不錯的選擇;但涉及多個回呼、多個狀態時,委派仍是最清晰的解法。