通知中心 (先注冊觀察者,後發送通知)
- (IBAction)buttonDidClicked:(UIButton *)sender {
SecondViewController *secondVC = [[SecondViewController alloc] init];
[self.navigationController pushViewController:secondVC animated:YES];
// 通知中心 *注冊* 觀察者
// 監聽 123 頻道消息
// 主要作用不是傳值,而是實作相隔較遠的頁面之間進行互動
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didReceiveNotification:) name:@"123" object:nil];
}
接收通知中心發送的通知
#pragma mark - 接收通知中心發送的通知
- (void)didReceiveNotification:(NSNotification *)sender
{
self.firstLabel.text = sender.userInfo[@"text"];
NSLog(@"welcome back!");
}
移除通知中心的觀察者(首選pop)
#pragma mark - 移除通知中心的觀察者(首選pop)
// 如果記憶體控制好的話,也可以在dealloc裡面寫,ARC下也可以寫dealloc
- (void)dealloc
{
// 移除所有的觀察者
[[NSNotificationCenter defaultCenter] removeObserver:self];
// 移除指定的觀察者
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"123" object:nil];
}
發送通知
- (IBAction)backButtonDidClicked:(UIButton *)sender {
// 發送通知
[[NSNotificationCenter defaultCenter] postNotificationName:@"123" object:nil userInfo:@{@"text":self.textField.text}];
[self.navigationController popViewControllerAnimated:YES];
}