什么是notification?
个人的理解,就是某个人在某个部门注册成为会员,也就是我们下面说道的注册称为监听者,让监听者替你监听某个事件,当监听者监听到某事件后,就发送通知:postNotification 给nsnotificationCenter,然后监听者执行选择器中的方法。下面简单介绍一下这个过程:
首先要注册监听器:
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(goChange:) name:@"ChangeColor" object:nil];
最后的object:后我们用的是nil 表明是给所有的监听者发送信息,如果写的是某一个对象,则只给该对象发送通知。
其中就我的考虑:NSNotificationCenter 就像是一个存放消息的容器,我们既可以向里面存放信息,也可以从里面提取信息。
goChange:方法的实现如下:
-(void)goChange:(NSNotification *)notification
{
//拿到通知内容。
NSDictionary *dic = [notification userInfo];
NSString *colorString = [dic objectForKey:@"color"];
UIColor *color = nil;
if ([colorString isEqualToString:@"red"]) {
color = [UIColor redColor];
} else if ([colorString isEqualToString:@"blue"]){
color = [UIColor blueColor];
}
self.view.backgroundColor = color;
}
redButton:
-(void)setRedColor
{
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"red" forKey:@"color"];
[[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeColor" object:self userInfo:dic] ;
}
blueButton:
-(void)setBlueColor
{
NSDictionary *dic = [NSDictionary dictionaryWithObject:@"blue" forKey:@"color"];
[[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeColor" object:self userInfo:dic];
}
然后就是这一句:
[[NSNotificationCenter defaultCenter]postNotificationName:@"ChangeColor" object:self userInfo:dic];
postNotification的作用是保存参数,并把这个建立的notification发送给NSNotificationCenter;
我的理解就是:当点击按钮的时候,看notificationName如果这个name跟postNotificationName相同,则通知发送成功,执行监听者选择器的方法。就达到了通知你个人的目的。
如有疑问,欢迎提出,这也是我刚开始写技术性的博客文章,肯定会有很多漏洞,欢迎批评指正,相信我会越做越好。