zoukankan      html  css  js  c++  java
  • iOS 通知中心

    原文地址 : http://www.jianshu.com/p/1208724e1915

    iOS 提供了一种 “同步的” 消息通知机制NSNotificationCenter,观察者只要向消息中心注册, 即可接受其他对象发送来的消息,消息发送者和消息接受者两者可以互相一无所知,完全解耦。
    消息机制常常用于在向服务器端请求数据或者提交数据的场景,在和服务器端成功交互后,需要处理服务器端返回的数据,或发送响应消息等,就需要用到消息机制

    一、通知相关的类

    1. NSNotification 这个类可以理解为一个消息对象,其中包含三个属性
      @property (readonly, copy) NSNotificationName name;//消息对象的唯一标识,用于辨别消息对象。
      @property (nullable, readonly, retain) id object;//
      @property (nullable, readonly, copy) NSDictionary *userInfo;//用来传递消息

      NSNotification的初始化方法:

       - (instancetype)initWithName:(NSNotificationName)name object:(nullable id)object userInfo:(nullable NSDictionary *)userInfo NS_AVAILABLE(10_6, 4_0) NS_DESIGNATED_INITIALIZER;
      - (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;
      + (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject;
      + (instancetype)notificationWithName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary *)aUserInfo;
      - (instancetype)init  //不能调用  /NS_UNAVAILABLE/;    / do not invoke; not a valid initializer for this class /

      注意:官方文档有明确的说明,不可以使用init进行初始化
    2. NSNotificationCenter这个类是通知中心,用单例设计,每个应用程序都会有一个默认的通知中心,用于调度通知的发送和接受。

      • 添加一个观察者,可以为它指定一个方法,名字和对象。接收到通知时,执行方法。

         - (void)addObserver:(id)observer selector:(SEL)aSelector name:(nullable NSNotificationName)aName object:(nullable id)anObject;

        参数解析:Observer:(谁来接受通知消息);selector(方法选择,执行哪个方法); name:(通知的名称,也可以说是通知消息的标识,按照这个来区分是否接受通知);object:(接受谁的通知(进行筛选),用这个参设置,nil为接受所有文件 发送的通知)。

      • 发送通知消息的方法

        - (void)postNotification:(NSNotification )notification;

        - (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject;

        - (void)postNotificationName:(NSNotificationName)aName object:(nullable id)anObject userInfo:(nullable NSDictionary )aUserInfo;

        参数解析:Name:(通知标识,与注册通知是的标识对应);object:(发送方);userInfo:(重点说一下,这是一个字典类型的对象,可以把需要传递 的值放进这个字典里)

    • 移除通知的方法

      - (void)removeObserver:(id)observer;

      - (void)removeObserver:(id)observer name:(nullable NSNotificationName)aName object:(nullable id)anObject;

      注意:1.如果发送的通知指定了object对象,那么观察者接收的通知设置的object对象与其一样,才会接收通知。但是接收通知如果将这个参数设置为nil则会接收一切通知。
      2.观察者的SEL函数指针可以有一个参数,参数就是发送的消息对象本身,可以通过这个参数取到消息对象的usetInfo,实现传值。

    二、通知的使用流程

    要想完成一个通知,主要有分三个执行步骤,而且是按顺序来的
    顺序很重要,顺序很重要,顺序很重要,重要的事情说三遍
    1.要保证注册通知在发送消息之前

    1. 首先,在需要接收通知的地方注册观察者,比如
       //获取通知中心单例对象
      NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
      //添加当前类对象为一个观察者,name和object设置为nil,表示接收一切通知
      [center addObserver:self selector:@selector(notice:) name:@"aha" object:nil];
    2. 然后,在我们需要时发送通知消息
      //创建消息对象
      NSNotification *notification = [[NSNotification alloc]initWithName:@"aha" object:@"hah" userInfo:@{@"我是消息":@"hello"}];
      //使用通知中心发送通知
      [[NSNotificationCenter defaultCenter]postNotification:notification];
    3. 最后移除通知
      //移除通知
      [[NSNotificationCenter defaultCenter]removeObserver:self name:@"aha" object:nil];

    三、通知知识注意事项及拓展

      1. 通知一般用在反向传值,如果要实现正向传值则必须保证:注册通知在发送通知之前实现
        可以参考:Mazy_ma的博客:iOS-通知正向传值问题

      2. 多个监听者监听同一个消息时:
        监听同一条通知的多个观察者,在通知到达时,它们执行回调的顺序是不确定的,所以我们不能去假设操作的执行会按照添加观察者的顺序来执行

      3. 关于注册监听者,还有一个需要注意的问题是,每次调用addObserver时,都会在通知中心重新注册一次,即使是同一对象监听同一个消息,而不是去覆盖原来的监听。这样,当通知中心转发某一消息时,如果同一对象多次注册了这个通知的观察者,则会收到多个通知。

      4. 默认的通知是同步的:
        代码如下:

        -(void)viewDidLoad {
         [super viewDidLoad];
         //注册通知观察者
         [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(comeTrueNotification:) name:kNotificationName object:@"wow"]; 
         UIButton *sendNoticeBtn = [UIButton   buttonWithType:UIButtonTypeSystem];
         [sendNoticeBtn setFrame:CGRectMake(100, 100, 100, 100)];
         [sendNoticeBtn setBackgroundColor:[UIColor cyanColor]];
         [sendNoticeBtn setTitle:@"sendBtn" forState:UIControlStateNormal];
         [self.view addSubview:sendNoticeBtn];
         [sendNoticeBtn addTarget:self action:@selector(sendNoticeBtnDown) forControlEvents:UIControlEventTouchUpInside];
        
         NSLog(@"%d,%@,viewDidLoad",__LINE__,[NSThread currentThread]);

        }

        -(void)comeTrueNotification:(NSNotification *)notification {

         NSString *message = notification.object;
         //执行消息方法
         NSLog(@"%d,%@,%@",__LINE__,[NSThread currentThread],message);
        
         sleep(5);
        
         NSLog(@"%d,%@,comeTrueNotification",__LINE__,[NSThread mainThread]);

        }
        -(void)sendNoticeBtnDown {

           //发送消息
         [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationName object:@"wow"];
        
         NSLog(@"%d,%@,sendNoticeBtnDown",__LINE__,[NSThread currentThread]);

        }


        运行结果:

        控制台展示.png

        可以参考好文:NSNotificationCenter的同步和异步
      5. 通知异步的处理方法:(参考:NSNotificationCenter的同步和异步

        • 通知异步方法一:
          让通知事件处理方法在子线程中执行:(例如:)
          dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
          sleep(5);
          });
        • 通知异步方法二:
          您可以通过NSNotificationQueue的enqueueNotification:postingStyle:和enqueueNotification:postingStyle:coalesceMask:forModes:方法将通告放入队列,实现异步发送,在把通告放入队列之后,这些方法会立即将控制权返回给调用对象。
          我们修改sendNoticeBtnDown事件如下:
          //发送消息
          NSNotification *notification = [NSNotification notificationWithName:kNotificationName object:@"wow"];
          [[NSNotificationQueue defaultQueue]enqueueNotification:notification postingStyle:NSPostASAP];
          // [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationName object:@"wow"];
          通过通知队列来管理通知,不会再造成阻塞
      6. 关于通知的移除
        虽然在 IOS 用上 ARC 后,不显示移除 NSNotification Observer 也不会出错,但是这是一个很不好的习惯,不利于性能和内存。
        注销观察者有2个方法:
        a. 最优的方法,在 UIViewController.m 中:

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

        b. 单个移除:
        [[NSNotificationCenter defaultCenter] removeObserver:self name:@"Notification_GetUserProfileSuccess" object:nil];
        注意:
        removeObserver:是删除通知中心保存的调度表一个观察者的所有入口,而removeObserver:name:object:是删除匹配了通知中心保存的调度表中观察者的一个入口。
        这个比较简单,直接调用该方法就行。例如:
        [[NSNotificationCenter defaultCenter] removeObserver:observer name:nil object:self];
        注意参数notificationObserver为要删除的观察者,一定不能置为nil。
  • 相关阅读:
    python—打开图像文件报错
    CTFshow萌新赛-萌新福利
    微信小程序bug
    微信小程序
    架构
    命令行
    MyBatis
    avalon
    并发测试工具
    less
  • 原文地址:https://www.cnblogs.com/ibelieveyou/p/6758917.html
Copyright © 2011-2022 走看看