通知中心 (先注册观察者,后发送通知)
- (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];
}