NSNotificationCenter 使用

2020-09-20  本文已影响0人  奇梦人
1. NSNotificationCenter 简介

NSNotificationCenter 是 IOS 内部一种消息广播的实现机制(对应Android 的BroadcastReceiver) ,可以在不同的对象之间发送通知。通知中心采用的是一对多的方式。
再IOS 9.0之后不需要移除监听,如果想兼容之前的版本需要 主动移除监听

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
2.具体使用
1. 注册监听】

- (void)viewDidLoad {
    [super viewDidLoad];
       // Do any additional setup after loading the view.
      [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_doTextViewAnimationWithNotification:) name:@"sendMessage" object:nil];
}


2. 再实现相关方法

- (void)_doTextViewAnimationWithNotification:(NSNotification *)noti{
    NSLog(@"收到消息 %@",@"sendMesage");
}

3. 发送消息

[[NSNotificationCenter defaultCenter] postNotificationName:@"sendMessage" object:nil ];
  1. 注意事项

很多时候我们使用的是第三方框架发送的通知,或是系统提供的通知,我们无法预知这些通知是否是在主线程中发送的,为了安全起见最好在需要更新UI时使用GCD将更新的逻辑放入主线程执行。

  1. 非主线程发送通知
   //使用GCD获取一个非主线程的线程用于发送通知
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:@"inputTextValueChangedNotification" object:nil userInfo:@{@"inputText": self.textField.text}];
    });
  1. GCD 切换到主线程
 //使用GCD获取主线程并更新UI
    dispatch_async(dispatch_get_main_queue(), ^{
        self.label.text = notification.userInfo[@"inputText"];
    });
上一篇 下一篇

猜你喜欢

热点阅读