NSNotification 消息通知的3种方式


1、Notification Center的概念:

  • 它是一个单例对象,允许当事件发生时通知一些对象,让对象做出相应反应。

  • 它允许我们在低程度耦合的情况下,满足控制器与一个任意的对象进行通信的目的。 这种模式的基本特征是为了让其他的对象能够接收到某种事件传递过来的通知,主要使用通知名称来发送和接收通知。

  • 基本上不用考虑其它影响因素,只需要使用同样的通知名称,监听该通知的对象(即观察者)再对通知做出反应即可。

  • 1)优势:

    • 1.不需要编写多少代码,实现比较简单;
    • 2.对于一个发出的通知,多个对象能够做出反应,简单实现1对多的方式,较之于 Delegate 可以实现更大的跨度的通信机制;
    • 3.能够传递参数(object和userInfo),object和userInfo可以携带发送通知时传递的信息。
  • 2)缺点:

    • 1.在编译期间不会检查通知是否能够被观察者正确的处理;
    • 2.在释放通知的观察者时,需要在通知中心移除观察者;
    • 3.在调试的时候,通知传递的过程很难控制和跟踪;
    • 4.发送通知和接收通知时需要提前知道通知名称,如果通知名称不一致,会出现不同步的情况;
    • 5.通知发出后,不能从观察者获得任何的反馈信息。

2、代码

  • 1、不传递参数, 最常用的一种

    • 发送通知
    -(void)btn1Click
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noti1" object:nil];
    }
    
    • 监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti1) name:@"noti1" object:nil];
    
    • 调用方法
    -(void)noti1
    {
        NSLog(@"接收 不带参数的消息");
    }
    
  • 2、使用object 传递消息

    • 发通知
    -(void)btn2Click:(UIButton *)btn
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noti2" object:[NSString stringWithFormat:@"%@",btn.titleLabel.text]];
    }
    
    • 监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti2:) name:@"noti2" object:nil];
    
    • 调用方法
    -(void)noti2:(NSNotification *)noti
    {
        // 使用object处理消息
        NSString *info = [noti object];
        NSLog(@"接收 object传递的消息:%@",info);
    }
    
  • 3、使用userInfo 传递消息

    • 发通知
    -(void)btn3Click
    {
        NSDictionary *dic = [NSDictionary dictionaryWithObject:@"userInfo消息" forKey:@"param"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"noti3" object:nil userInfo:dic];
    }
    
    • 监听
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti3:) name:@"noti3" object:nil];
    
    • 调用方法
    -(void)noti3:(NSNotification *)noti
    {
        // 使用userInfo处理消息
        NSDictionary  *dic = [noti userInfo];
        NSString *info = [dic objectForKey:@"param"];
        NSLog(@"接收 userInfo传递的消息:%@",info);
    }
    
  • 最后,记得在发送通知消息的页面,在dealloc方法里面移除观察者。

    -(void)dealloc
    {
        // 移除观察者,Observer不能为nil
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
原文地址:https://www.cnblogs.com/CH520/p/9237211.html