NSNotification是同步操作

原文

在抛出通知以后,观察者在通知事件处理完成以后,抛出者才会往下继续执行,也就是说这个过程默认是同步的;当发送通知时,通知中心会一直等待所有的observer都收到并且处理了通知才会返回到poster;

若要改为异步:

方法1:

- (void) actionNotification: (NSNotification*)notification
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString* message = notification.object;
        NSLog(@"%@",message);
    });
}

方法2:

可以通过
NSNotificationQueue的enqueueNotification: postingStyle:和enqueueNotification: postingStyle: coalesceMask: forModes:
方法将通告放入队列,实现异步发送,在把通告放入队列之后,这些方法会立即将控制权返回给调用对象。

- (void)buttonDown
{
    NSNotification *notification = [NSNotification notificationWithName:kNotificationName
                                                                 object:@"通知说话开始"];
    [[NSNotificationQueue defaultQueue] enqueueNotification:notification
                                               postingStyle:NSPostASAP];
    //[[NSNotificationCenter defaultCenter] postNotificationName:kNotificationName object:@"通知说话开始"];
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容