應用場景:有時候從介面 A 跳轉到介面 B,當介面 B 返回時,需要將處理的結果回傳給介面 A。這時就可以透過代理來實現反向傳值。
1、定義一個負責傳值的協議(protocol),介面 A 擁有該協議的屬性並實作協議中的方法;
2、介面 B 同樣持有該協議屬性(代理要求雙方都引用同一個物件),在返回時取得介面 A 的引用指標,將 B 中協議的呼叫目標設為 A,再呼叫協議中的傳值方法。
#import <UIKit/UIKit.h>
@protocol PassValueDelegate <NSObject>
- (void)setValue:(NSString *)param;
@end
@interface ViewController : UIViewController
@property (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];
}
- (void)setValue:(NSString *)param {
NSLog(@"pass value is:%@", param);
}
- (void)btn
{
[self.navigationController pushViewController:[[ViewController2 alloc] init] animated:YES];
}
@end介面 B 在私有類別延伸中持有代理屬性,並在返回時將自身 delegate 指向導航堆疊中的 A:
#import "ViewController2.h"
#import "ViewController.h"
@interface ViewController2 ()
@property (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
{
self.passValueDelegate = self.navigationController.childViewControllers[0];
[self.navigationController popToRootViewControllerAnimated:YES];
[self.passValueDelegate setValue:@"123456789"];
}
@end透過這種代理機制,介面 B 便能在返回前把結果回傳給介面 A,實現頁面的反向資料傳遞。