iOS 的頁面傳值大致可以歸納為四種:代理(Delegate)、Block、通知(NSNotification)與單例(Singleton)。本文用一個最典型的情境把它們逐一實作出來。
有兩個頁面,各自帶一個 Button。點擊首頁的按鈕推入第二頁,再點擊第二頁的按鈕跳回首頁,此時首頁按鈕的標題要變成第二頁傳回的字串。
代理一直是我的心結——API 都會用,卻寫不出自己的。釐清這件事有個簡單的思考方式:
第二頁想要修改第一頁的資料,但它自己做不到,所以需要一個代理幫它完成這件事。因此協議與 delegate 屬性都定義在第二頁,而第一頁負責實作並把自己交出去。
第二頁宣告協議與 delegate 屬性:
@protocol change <NSObject> - (void)changeButton:(NSString *)string; @end @interface realendVC : UIViewController @property (weak, nonatomic) IBOutlet UIButton *realendBtn; @property (nonatomic, weak) id<change> delegate; @end
第二頁在返回前呼叫代理方法:
- (IBAction)click:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
if (self.delegate) {
[self.delegate changeButton:@"成功"];
}
}
第一頁建立第二頁時把自己設為代理,並實作代理方法:
@interface frontVC () {
realendVC *realendvc; // 第二個頁面
}
@end
@implementation frontVC
- (void)viewDidLoad {
[super viewDidLoad];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
realendvc = [storyboard instantiateViewControllerWithIdentifier:@"second"];
realendvc.delegate = self;
}
- (IBAction)click:(id)sender {
[self.navigationController pushViewController:realendvc animated:YES];
}
#pragma mark - 代理方法
- (void)changeButton:(NSString *)string {
[_frontBtn setTitle:string forState:UIControlStateNormal];
}
@end
第二頁對外暴露一個 block 屬性:
typedef void (^MyBlock)(NSString *); @interface realendVC : UIViewController @property (weak, nonatomic) IBOutlet UIButton *realendBtn; @property (copy, nonatomic) MyBlock myblock; @end
- (IBAction)click:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
self.myblock(@"成功");
}
第一頁在取得第二頁實例後直接賦值。這裡有個細節:Block 內只能讀取外部變數,若要修改得加 __block;本例只是要呼叫 setTitle:,屬於對物件狀態的修改而非變數重新賦值,但加上 __block 仍是常見且安全的寫法:
__block UIButton *button = _frontBtn;
realendvc.myblock = ^(NSString *string) {
[button setTitle:string forState:UIControlStateNormal];
};
第一頁註冊觀察者並處理通知:
- (void)viewDidLoad {
[super viewDidLoad];
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
realendvc = [storyboard instantiateViewControllerWithIdentifier:@"second"];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(change:)
name:@"button"
object:nil];
}
- (void)change:(NSNotification *)notification {
[_frontBtn setTitle:(NSString *)[notification object] forState:UIControlStateNormal];
}
第二頁送出通知:
- (IBAction)click:(id)sender {
[self.navigationController popViewControllerAnimated:YES];
[[NSNotificationCenter defaultCenter] postNotificationName:@"button" object:@"成功"];
}
別忘了在 dealloc 中移除觀察者,否則可能收到已釋放物件而崩潰:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
把要傳遞的資料放在一個單例類的屬性上,第二頁寫入、第一頁讀出即可。這種方式最簡單,但缺點也最明顯:資料成為全域狀態,多個頁面同時操作時容易互相干擾,不適合傳遞與特定頁面生命週期綁定的資訊。
Delegate 語意最清楚,適合一對一且關係穩定的回傳;Block 寫法精簡、上下文集中,適合一次性的回調;通知適合一對多、發送者與接收者互不相識的廣播情境;單例則留給真正需要全域共享的設定資料。另外還有第五種常見做法——利用 Segue 的 prepareForSegue:sender: 在跳轉前傳值,在 Storyboard 專案中往往比上述幾種都自然。