简体   繁体   中英

Is dispatch_async(dispatch_get_main_queue(), …) necessary in this case?

I came across this piece of code, and I can't quite figure out why the author did this. Take a look at this code:

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

I have a method with a completion block, and in this block a notification has to be posted. I don't quite understand why the dispatch_async on the main queue is necessary in this case. The block will already be run on the main thread, and even if it wasn't I don't think it would really matter would it? I would simply have written this:

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

And it does work in my testing.

If you can help me shed some light on this, I'd really appreciate it!

Matt

These 2 sentences from the NSNotificationCenter Class Reference suggest a couple of possible reasons:

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.

So perhaps (a) the author doesn't want the code to block until all observers have processed the notification, and/or (b) he wants to ensure that the observer methods run on the main thread.

Sometimes you need to run methods that fire some execution asynchronously and return right away. Eg some of the AppDelegate 'key' methods like applicationDidBecomeActive , or applicationDidEnterBackground , need to be executed and return quickly so the OS doesn't kill your app.

I don't know if that is the case of your question, but it is a possible explanation of the usage of dispatch_async .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM