您的位置:首页 > 其它

NSNotificationCenter通知基本用法(一)

2016-06-28 21:36 316 查看
ViewController.m文件中

- (void)viewDidLoad {
[super viewDidLoad];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveChangeColorNotification:) name:@"changeColorNotification" object:nil];
}

- (void)receiveChangeColorNotification:(NSNotification *)noti{
//通知调用方法时传得参数是NSNotification,
self.view.backgroundColor = [noti.userInfo objectForKey:@"color"];
}

- (IBAction)gotoSecondVC:(UIButton *)sender {
SecondVC *vc = [[SecondVC alloc] init];
[self.navigationController pushViewController:vc animated:YES];
[vc release];
}


SecondVC.m中

- (void)viewDidLoad {
[super viewDidLoad];
//通知和代理相同之处:都可以实现方法调用和传值。
//不同之处:通知可以多对多传值和调用,而代理只能一对一。  通知只能实现单向传值,而代理可以实现值的回传。
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//addObserver添加观察者(监听通知)
//第一个参数是添加的观察者(让谁监听)
//第二个参数是收到通知后调用的方法
//第三个参数是要监听的通知的名字(写nil的话监听所有通知)
//第四个参数是限定通知来源(写nil的话不限定通知来源)
[center addObserver:self selector:@selector(receiveChangeColorNotification:) name:@"changeColorNotification" object:nil];
}

- (void)receiveChangeColorNotification:(NSNotification *)noti{
//通知调用方法时传得参数是NSNotification,
if (noti.object != self) {
self.view.backgroundColor = [noti.userInfo objectForKey:@"color"];
}
}

- (IBAction)colorButtonClick:(UIButton *)sender {
UIColor *color = sender.tag == 1?[UIColor redColor]:sender.tag == 2?[UIColor greenColor]:[UIColor blueColor];
//通知中心,也是单例类。发通知必须通过通知中心
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
//postNotificationName发送一个通知。
//第一个参数name表示通知的名字。
//第二个参数object表示通知的发送者。
//第三个参数userInfo是通知的参数,是一个字典。
[center postNotificationName:@"changeColorNotification" object:self userInfo:@{@"color":color}];
}

- (void)dealloc{
//removeObserver取消某个对象的通知监听。
//*一个对象在被释放前一定要取消通知的监听,否则系统在发这个对象所监听的通知时,系统就会崩溃。
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: