在主线程上发布NSNotification [英] Posting NSNotification on the main thread

查看:143
本文介绍了在主线程上发布NSNotification的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了以下代码片段,它允许 NSNotification 在任何后台线程的主线程上发布。我想知道这是否是一个安全且可接受的做法。

I found the following code snippet which allows NSNotification to be posted on the main thread from any background thread. I would like to know if this is a safe and acceptable practice please?

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"ImageRetrieved" 
                                                        object:nil 
                                                      userInfo:imageDict];
});


推荐答案

一般来说,您希望NSNotifications在主体上发送,特别是如果他们触发UI活动,例如关闭一个模态登录对话框。

Generally you want the NSNotifications to be sent on the main , especially if they trigger UI activities like dismissing a modal login dialog.

将通知传递到特定主题


定期通知中心会在
的通知中发送通知,通知已发布。分布式通知中心
在主线程上传递通知。有时,您可能需要在您由您(而不是通知中心)确定的
的特定主题上传送
通知。例如,如果
在后台线程中运行的对象正在侦听来自用户界面的
通知,例如窗口关闭,则
想要在后台线程中接收通知
而不是主线程。在这些情况下,您必须捕获
通知,因为它们在默认线程上传递,并将
重定向到相应的线程。

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.

这篇关于在主线程上发布NSNotification的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆