objective-c - 在这种情况下是否需要 dispatch_async(dispatch_get_main_queue(), ...) ?

标签 objective-c cocoa-touch objective-c-blocks grand-central-dispatch

我偶然发现了这段代码,我不太明白作者为什么这样做。看看这段代码:

someMethodStandardMethodUsingABlock:^() {
    dispatch_async(dispatch_get_main_queue(), ^{
        [[NSNotificationCenter defaultCenter] postNotificationName:"notif" object:nil];
    });
}];

我有一个带有完成 block 的方法,在这个 block 中必须发布一个通知。我不太明白为什么在这种情况下主队列上的 dispatch_async 是必要的。该 block 将已经在主线程上运行,即使不是,我也不认为这真的很重要,不是吗?我会简单地写这个:

someMethodStandardMethodUsingABlock:^() {
    [[NSNotificationCenter defaultCenter] postNotificationName:"notif" object:nil];
}];

它在我的测试中确实有效。

如果您能帮助我阐明这一点,我将不胜感激!

马特

最佳答案

NSNotificationCenter 类引用中的这两句话提​​出了几个可能的原因:

A notification center delivers notifications to observers synchronously. In other words, the postNotification: methods do not return until all observers have received and processed the notification.

...

In a multithreaded application, notifications are always delivered in the thread in which the notification was posted, which may not be the same thread in which an observer registered itself.

所以也许 (a) 作者不希望代码在所有观察者都处理完通知之前阻塞,和/或 (b) 他想确保观察者方法在主线程上运行。

关于objective-c - 在这种情况下是否需要 dispatch_async(dispatch_get_main_queue(), ...) ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9561604/

相关文章:

ios - 无法让 NSMutableDictionary 工作(xcode)

ios - 为使用的不同第 3 方库创建带有内部 Pod 的私有(private)框架的框架程序

objective-c - 什么是花栗鼠? (除了是一个物理引擎)

objective-c - ios 中的 __block 和 CLGecoder 问题?

objective-c - 为什么这个 uint32_t 在内存中是这样排序的?

ios - objective-c 区分 applicationWillResignActive 中的警报消息和任务切换器

objective-c - 定义方法时,我在 Objective-C 中的语法有什么问题?

objective-c - 在 iOS 的 Objective-C 中创建带有完成 block 的可中断动画?

objective-c - 将 Objective-C block 转换为 Swift 闭包

ios - 多个 block 数据调用完成时如何通知