关于NSNotification你可能不知道的东西

作者: 是的蛮大人 | 来源:发表于2016-11-25 11:24 被阅读307次

NSNotification,又叫通知,属于设计模式中的观察者模式,在开发中很常见,相信大家都不陌生。关于NSNotification的用法以及它与delegate的区别,都是些老生常谈的话题了,这里就不再说了。这篇文章主要想说几个平时开发过程中,大家可能都没有注意到的细节,我相信,当你理解了这些细节,你对NSNotification的认识会上升到另一个高度。

1、NSNotificationCenter是一种“同步”机制

先看看官方文档的一段说明(Xcode->Window->Documentation And API Reference,搜索NSNotification):

A notification center delivers notifications to observers synchronously. In other words, when posting a notification, control does not return to the poster until all observers have received and processed the notification.

意思是,当notification center post了一个notification后,只有当所有observer接收了notification并且处理完了后程序才会返回,才会继续执行post下面的代码。
我们写段代码来验证一下,也帮助加深理解。

  • 注册通知
 - (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNotification:) name:kNotificationName object:nil];
}
  • 处理通知
    注意这里将线程休眠了5秒
 - (void)handleNotification:(NSNotification *)notification {
    
    NSString *msg = [NSString stringWithFormat:@"receive notification:%@", notification.object];
    NSLog(@"%@", msg);
    
    //休眠5s
    sleep(5);
    
    NSLog(@"notification handle finish...");
}
  • 发送通知
 - (IBAction)pushOnMainThread:(id)sender {
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"pushOnMainThread"];
    
    NSLog(@"return...");
}

看下执行结果

可以看到,当我们postNotification后,Observer接收到notification并处理,确实是只有当Observer处理完成后(休眠了5s)程序才执行了postNotification后的代码(打印return...),而且这期间主屏幕会卡主(因为同步执行,要等待程序返回)

由此可见:** 接收到通知后不易做耗时操作,否则可能会卡住主线程,导致屏幕卡顿。**
另外,提一下,可以通过Notification Queues实现异步发送通知(暂时没去研究...😳)

2、NSNotificationCenter可以在多线程里执行

还是先看一下官方文档的说明:

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

意思是,** notification在哪个线程里post,Observer就会在哪个线程里接收并处理,这个线程可能不是最初Observer被添加的线程。 **
在上面那段代码里,我们是在主线程上添加的Observer(viewDidLoad里)
我们现在通过子线程post一个notification看看结果:

  • handleNotification里打印当前线程
 - (void)handleNotification:(NSNotification *)notification {
    
    NSString *msg = [NSString stringWithFormat:@"receive notification:%@[%@]", notification.object, [NSThread currentThread]];
    NSLog(@"%@", msg);
}
  • 子线程中postNotification
 - (IBAction)pushOnOtherThread:(id)sender {
    
    dispatch_queue_t queue = dispatch_queue_create("test", DISPATCH_QUEUE_CONCURRENT);
    dispatch_async(queue, ^{
        NSLog(@"post notification on other thread..%@",[NSThread currentThread]);
        [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"pushOnOtherThread"];
    });
}

执行结果如下:


可以看到,正如官方文档里说明的那样,当我们在其他线程里postNotification时,Observer确实是在那个线程里执行的。
所以,这里就会有个坑,当你要在Observer里更新UI的时候,如果notification是在其他线程里post的,那就可能会出现一些奇怪的问题了,比如主线程不响应,甚至是crash(注意crash不是必然的)。

  • handleNotification里更新UI,异步postNotification
 - (void)handleNotification:(NSNotification *)notification {
    
    NSString *msg = [NSString stringWithFormat:@"receive notification:%@[%@]", notification.object, [NSThread currentThread]];
    self.msgLabel.text = msg;
    
    NSLog(@"%@", msg);
}
  • 执行结果
    程序没有crash,msgLabel上的text确实正确显示出来了,不过是延迟了几秒钟后才显示出来的。同时在控制台里会出现下面这段内容:


可以看到,接收到notification后又过了6秒,系统给出了一段说明,告知这个操作可能会导致奇怪的crash,但不是必定会crash,但是这种操作应该被避免。

结束语

说了一大堆,其实对平时开发可能帮助不大,因为大家已经习惯了在主线程里addObserver、postNotification,可能完全不会在意它可不可以在多线程里运行。Who care!
But! 如果你知道了这些,可能会对以后面试有帮助哦~~~😀😀😀

相关文章

  • 关于NSNotification你可能不知道的东西

    NSNotification,又叫通知,属于设计模式中的观察者模式,在开发中很常见,相信大家都不陌生。关于NSNo...

  • 关于NSNotification

    通知应该是日常开发经常会用到的,但是实际上有很多东西和自己理解的并不一样。这次遇到一个bug就是 接受通知之后执行...

  • 深入理解iOS NSNotification

    NSNotification在平时开发中使用非常频繁。网上关于NSNotification介绍大多是停留在用法的介...

  • 深入理解iOS NSNotification

    NSNotification在平时开发中使用非常频繁。网上关于NSNotification介绍大多是停留在用法的介...

  • 学习笔记-通知

    关于通知 1.消息源 创建通知NSNotification *notifiction = [NSNotificat...

  • iOS底层系列31 -- Notification的底层原理

    关于NSNotification通知的源码下载地址点击这里[http://wwwmain.gnustep.org/...

  • 二龙的第6次课

    关于二龙说自己不会的回应 不是你不会,而是你不知道有更好的办法。 关于好东西(玩具)很多,不可能都买回家 不围绕和...

  • NSNotification

    发通知 NSNotification *deleteMyCommemtN =[NSNotification not...

  • iOS通知中心

    有关的类 NSNotification NSNotificationCenter NSNotification N...

  • 通知使用

    创建对象 NSNotification *notification =[NSNotification notifi...

网友评论

本文标题:关于NSNotification你可能不知道的东西

本文链接:https://www.haomeiwen.com/subject/tcbipttx.html