NSNotificationCenter 注意

  • 成对出现
  • 意思很简单,NSNotificationCenter消息的接受线程是基于发送消息的线程的。也就是同步的,因此,有时候,你发送的消息可能不在主线程,而大家都知道操作UI必须在主线程,不然会出现不响应的情况。所以,在你收到消息通知的时候,注意选择你要执行的线程。下面看个示例代码

    //接受消息通知的回调
    - (void)test
    {
        if ([[NSThread currentThread] isMainThread]) {
            NSLog(@"main");
        } else {
            NSLog(@"not main");
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            //do your UI
        });
    
    }
    
    //发送消息的线程
    - (void)sendNotification
    {
        dispatch_queue_t defaultQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(defaultQueue, ^{
            [[NSNotificationCenter defaultCenter] postNotificationName:@"test" object:nil];
        });
    }


    文/JamesYu(简书作者)
    原文链接:http://www.jianshu.com/p/a4d519e4e0d5
    著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”。
原文地址:https://www.cnblogs.com/dzhs/p/5606887.html