iOS之OC深入理解首页投稿(暂停使用,暂停投稿)iOS Developer

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

2016-11-25  本文已影响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];
}
 - (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看看结果:

 - (void)handleNotification:(NSNotification *)notification {
    
    NSString *msg = [NSString stringWithFormat:@"receive notification:%@[%@]", notification.object, [NSThread currentThread]];
    NSLog(@"%@", msg);
}
 - (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不是必然的)。

 - (void)handleNotification:(NSNotification *)notification {
    
    NSString *msg = [NSString stringWithFormat:@"receive notification:%@[%@]", notification.object, [NSThread currentThread]];
    self.msgLabel.text = msg;
    
    NSLog(@"%@", msg);
}

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

结束语

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

上一篇下一篇

猜你喜欢

热点阅读