Delegate 是 iOS 中回傳資料最經典的方式,特別適合「第二個畫面向第一個畫面回傳結果」這種情境,例如從設定頁選完選項後把值帶回上一頁。
先在第 2 個 ViewController 中宣告一個協議,並提供一個 delegate 屬性:
// 定義協議,繼承自 NSObject 協議 @protocol ChuanZhiDelegate- (void)chuanzhid; @end @interface ViewController2 : UIViewController // delegate 用 assign 修飾,避免循環引用 @property (nonatomic, assign) id chuanzhidelegate; @end
- (void)viewDidLoad
{
[super viewDidLoad];
self.view.backgroundColor = [UIColor cyanColor];
self.btn = [[UIButton alloc] initWithFrame:CGRectMake(70, 100, 100, 30)];
self.btn.backgroundColor = [UIColor redColor];
[self.view addSubview:self.btn];
[self.btn addTarget:self action:@selector(chuan) forControlEvents:UIControlEventTouchUpInside];
}
- (void)chuan
{
// 呼叫前先檢查對方是否實作了這個方法
if ([self.chuanzhidelegate respondsToSelector:@selector(chuanzhid)])
{
[self.chuanzhidelegate chuanzhid];
}
else
{
NSLog(@"代理沒有實作 chuanzhid 方法");
}
}
respondsToSelector: 這個檢查很重要。協議裡宣告的方法可以是 @optional,即使全部標為 @required,動態語言下仍然可能出現對方尚未實作的情況,加上這個判斷可以避免 crash。
- (void)viewDidLoad
{
[super viewDidLoad];
self.btn = [[UIButton alloc] initWithFrame:CGRectMake(70, 100, 100, 30)];
self.btn.backgroundColor = [UIColor redColor];
[self.view addSubview:self.btn];
[self.btn addTarget:self action:@selector(chuanzhi) forControlEvents:UIControlEventTouchUpInside];
self.view.backgroundColor = [UIColor lightGrayColor];
}
- (void)chuanzhi
{
ViewController2 *vc = [[ViewController2 alloc] init];
vc.chuanzhidelegate = self; // 關鍵:把自己設為對方的代理
[self.navigationController pushViewController:vc animated:YES];
}
// 實作協議方法
- (void)chuanzhid
{
NSLog(@"代理已實作");
}
三個環節缺一不可:定義協議 → 建立關係(A 把自己設給 B)→ B 在時機到來時回呼 A。少掉任何一項,傳值都不會發生。
上面的範例只示範了「通知」而沒有攜帶資料。實務上通常會把參數帶進協議方法:
@protocol ChuanZhiDelegate- (void)chuanzhidWithResult:(NSString *)result; @end
呼叫端與實作端各自對應修改即可。另外,在 ARC 專案中 delegate 屬性建議改用 weak 而非 assign,語意更清楚,也能在對方被釋放後自動置為 nil,避免野蠻指標問題。