通知中心,它是IOS程序内部的一种消息广播机制,通过它,可以实现无引用关系的对象之间的通信。通知中心他是基于观察者模式,它只能进行程序内部通信,不能跨应用程序进程通信。当通知中心接受到消息后会根据设置,将消息发送给订阅者,这里的订阅者可以有多个。

  通知中心与代理模式类似,都可以实现多个对象间通信,通知中心可以将一个通知发送给多个监听者,而代理模式每个对象只能添加一个代理。但无论是那种模式,都是一种低耦合的设计,实现对象间的通信。

使用通知中心的步骤

1、注册观察者对某个事件(以字符串命名)感兴趣,并设置该事件触发时执行的Selector或Block

2、NSNotificationCenter在某个时机激发事件(以字符串命名)

3、观察者在收到感兴趣的事件时,执行相应地Selector或Block

4、移除通知

通知中心案例

  利用导航添加三个界面,在第三个界面上添加一组按钮,当点击按钮的时候,设置当前页面背景色为按钮颜色,并发送通知,将前面两个界面背景色也设置为选择的颜色,程序框架和界面如图所示

  (1)注册通知,在界面三的viewDidLoad方法中,为界面一和界面二注册通知,当发送通知的时候,会去界面一和界面二中调用对应的方法

  界面三中代码:

- (void)viewDidLoad {
[super viewDidLoad]; SecondViewController *secondVC = [self.navigationController.viewControllers objectAtIndex:];
ViewController *firstVC = [self.navigationController.viewControllers firstObject];
//注册通知
[[NSNotificationCenter defaultCenter] addObserver:secondVC selector:@selector(changeBgColor:) name:kNotificationName object:nil];
[[NSNotificationCenter defaultCenter] addObserver:firstVC selector:@selector(changeBgColor:) name:kNotificationName object:nil];
}

  ps:kNotificationName 是通过宏定义定义的字符串

  (2)    在界面三点击颜色按钮时,换背景色,并且给界面一和界面二发送通知

  界面三中代码:

- (IBAction)chooseBgColor:(UIButton *)sender {

    NSArray *colorArray = @[[UIColor redColor],[UIColor blueColor],[UIColor greenColor],[UIColor purpleColor],[UIColor whiteColor],[UIColor blackColor],[UIColor orangeColor],[UIColor yellowColor],[UIColor brownColor]];

    self.view.backgroundColor = [colorArray objectAtIndex:sender.tag-];

    //引发通知
[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:[colorArray objectAtIndex:sender.tag-]]; }

  (3)在界面一和界面二中处理通知,更改界面背景色

  界面一和界面二中代码:

-(void)changeBgColor:(NSNotification *)notification
{
[self.view setBackgroundColor:notification.object];
}

  (4)在界面三移除通知,移除通知一般在重写父类的dealloc方法,但是arc方式下,在dealloc方法中不能调用父类的dealloc方法

  界面三中代码:

-(void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:kNotificationName];
}

  想要了解更多内容的小伙伴,可以点击查看源码,亲自运行测试。

  疑问咨询或技术交流,请加入官方QQ群: (452379712)

作者:杰瑞教育
出处:http://www.cnblogs.com/jerehedu/ 
本文版权归烟台杰瑞教育科技有限公司和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
 

最新文章

  1. 使用Grunt 插件打包Electron Windows应用
  2. 如何优雅的实现INotifyPropertyChanged接口
  3. POJ 2155 Matrix (二维线段树)
  4. centos 升级 python后 python-setuptools pip 安装依赖报错
  5. MySQL配置管理
  6. 146. LRU Cache
  7. nginx日志格式含义
  8. windos下安装PEAR 注意
  9. mmap。
  10. hdu 1150 Machine Schedule(最小顶点覆盖)
  11. Xamarin android使用Sqlite做本地存储数据库
  12. PDA开发数据由本地上传至DB
  13. codeforces 1151 A
  14. 关于http与https的注意点
  15. vue从入门到进阶:指令与事件(二)
  16. Python 基于时间的进程通信
  17. java web 乱码终结
  18. linux 中的 open() read() write() close() 函数
  19. python 生成器与协程
  20. [jQ/PHP]使用JS数组储值的两种情况(提交PHP处理)

热门文章

  1. java 读入文件 BufferedReader
  2. JS中关于换行的2个坑
  3. React Native 系列(六)
  4. hashMap原理剖析
  5. 【BZOJ 2298】 2298: [HAOI2011]problem a (DP)
  6. android jni c C++ 实现下载
  7. java switch
  8. Eclipse下使用Stanford CoreNLP的方法
  9. [bzoj1019][SHOI2008]汉诺塔 (动态规划)
  10. FIS构建工具学习(一)