美文网首页
多线程通知

多线程通知

作者: 爱吃萝卜的小蘑菇 | 来源:发表于2019-03-20 11:05 被阅读0次

    摘录自:https://www.cnblogs.com/wangyang1213/p/5234228.html

    首先看下苹果的官方说明:

    Regular notification centers deliver notifications on the thread in which the notification was posted. Distributed notification centers deliver notifications on the main thread. At times, you may require notifications to be delivered on a particular thread that is determined by you instead of the notification center. For example, if an object running in a background thread is listening for notifications from the user interface, such as a window closing, you would like to receive the notifications in the background thread instead of the main thread. In these cases, you must capture the notifications as they are delivered on the default thread and redirect them to the appropriate thread.

    意思很简单,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];
        });
    }
    

    相关文章

      网友评论

          本文标题:多线程通知

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