從介面 A 跳轉到介面 B,B 處理完畢返回時,需要把結果回傳給 A。這類「反向傳值」在 iOS 中最直觀的做法就是 delegate。
1、定義一個負責傳值的協議,介面 A 宣告該協議的屬性並實作協議中的方法。
2、介面 B 同樣持有該協議類型的屬性(兩者引用同一個協議定義),返回前取得介面 A 的引用,把 B 中協議的調用目標指向 A,再呼叫協議方法完成傳值。
#import <UIKit/UIKit.h> @protocol passValueDelegate <NSObject> - (void)setValue:(NSString *)param; @end @interface ViewController : UIViewController @property (nonatomic, weak) id<passValueDelegate> passValueDelegate; @end
#import "ViewController.h"
#import "ViewController2.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 200, 40);
[btn setTitle:@"btn" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
self.view.backgroundColor = [UIColor redColor];
}
// 協議方法的實作:接收 B 傳回來的值
- (void)setValue:(NSString *)param {
NSLog(@"pass value is:%@", param);
}
- (void)btn {
[self.navigationController pushViewController:[[ViewController2 alloc] init] animated:YES];
}
@end
#import <UIKit/UIKit.h> @interface ViewController2 : UIViewController @end
#import "ViewController2.h"
#import "ViewController.h"
@interface ViewController2 ()
@property (nonatomic, weak) id<passValueDelegate> passValueDelegate;
@end
@implementation ViewController2
- (void)viewDidLoad {
[super viewDidLoad];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame = CGRectMake(100, 100, 200, 40);
[btn setTitle:@"back" forState:UIControlStateNormal];
[btn addTarget:self action:@selector(btn) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
}
- (void)btn {
// 把代理指向 A,也就是導航堆疊中的根控制器
self.passValueDelegate = self.navigationController.childViewControllers[0];
[self.navigationController popToRootViewControllerAnimated:YES];
[self.passValueDelegate setValue:@"123456789"];
}
@end
delegate 屬性務必宣告為 weak,否則 A 持有 B、B 又持有 A,會形成循環引用導致兩者都無法釋放。
呼叫協議方法前加上 respondsToSelector 判斷會更健壯,因為並非所有遵循者都一定實作了可選方法。
另外,示範中透過 navigationController.childViewControllers[0] 取得 A 的方式,只適合堆疊結構固定的簡單情境。若層級較深或有多條跳轉路徑,更可靠的做法是在 push 之前先由 A 設定 b.passValueDelegate = self,讓依賴關係明確寫在程式碼裡。