您的位置:首页 > 移动开发 > IOS开发

iOS_NSNotificationCenter(通知中心简单建立)

2015-07-22 19:00 531 查看
通知中心 (先注册观察者,后发送通知)

- (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];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: