IOS NSNotification Center 通知中心的使用

  通知中心,它是IOS程序内部的一种消息广播机制。通过它。能够实现无引用关系的对象之间的通信。

通知中心他是基于观察者模式,它仅仅能进行程序内部通信,不能跨应用程序进程通信。当通知中心接受到消息后会依据设置,将消息发送给订阅者,这里的订阅者能够有多个。

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

使用通知中心的步骤

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

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

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

4、移除通知

通知中心案例

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

 

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

  界面三中代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    
    SecondViewController *secondVC = [self.navigationController.viewControllers objectAtIndex:1];
    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)    在界面三点击颜色button时,换背景色,而且给界面一和界面二发送通知

  界面三中代码:

- (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-1];
    
    //引发通知
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:[colorArray objectAtIndex:sender.tag-1]];
  
}

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

  界面一和界面二中代码:

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


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

  界面三中代码:

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

  想要了解很多其它内容的小伙伴。能够点击查看源代码,亲自执行測试。

  疑问咨询或技术交流。请增加官方QQ群:JRedu技术交流 (452379712)

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

 
原文地址:https://www.cnblogs.com/cxchanpin/p/6882716.html