NSNotification 同步、异步

NSNotification 发通知的操作是同步的,并且通知处理是在发通知的那个线程

如下面的操作:

+ (void)postNotificationAsy {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
        [[NSThread currentThread] setName:@"test_notifi_thread"];
        NSLog(@"begin post notification....");
        [[NSNotificationCenter defaultCenter] postNotificationName:testNotification object:nil];
        NSLog(@"post notificaition finished...");
    });

}

// 这个通知回调方法是在线程 test_notifi_thread 处理的
- (void)handleNotification:(NSNotification *)notification {
    NSLog(@"handle thread name: %@",[NSThread currentThread].name);
    NSLog(@"handle Notification...");
}

打印结果:
 ThreadTest[5103:76211] begin post notification....
 ThreadTest[5238:83489] handle thread name: test_notifi_thread
 ThreadTest[5103:76211] handle Notification...
 ThreadTest[5103:76211] post notificaition finished...

1.在test_nofifi_thread线程中发一条通知 (异步通知)
2.postNotificationName这个方法没有立即返回,说明是同步的,它会执行完对应的回调的方法
3.通知回调处理是在发通知的线程(test_nofifi_thread)里处理的
4.postNotificationName这个方法实现,应该是在调用线程里去遍历所有的的NotificationName为Key的Observer列表,然后Observer调用对应注册的通知处理方法。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 近期接触项目中用的通知比较多,对于通知有一个系统的理解与学习,已下是做的一些总结 先来看看官方的文档,是这样写的:...
    9de75b652cd9阅读 623评论 0 0
  • NSNotificationCenter对象(通知中心)提供了在程序中广播消息的机制,它实质上就是一个通知分发表。...
    9de75b652cd9阅读 764评论 0 1
  • 转载自南峰子的技术博客 一个NSNotificationCenter对象(通知中心)提供了在程序中广播消息的机制,...
    我消失1314阅读 922评论 0 2
  • 本文主要讲了java中多线程的使用方法、线程同步、线程数据传递、线程状态及相应的一些线程函数用法、概述等。 首先讲...
    李欣阳阅读 2,509评论 1 15
  • 一个NSNotificationCenter对象(通知中心)提供了在程序中广播消息测机制,它实质上就是一个通知分发...
    DomAndMona阅读 822评论 0 2