MGA
MGA

Reputation: 3751

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

Upvotes: 5

Views: 6003

Answers (2)

Lio
Lio

Reputation: 4282

Sometimes you need to run methods that fire some execution asynchronously and return right away. E.g. 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.

Upvotes: 0

David Gelhar
David Gelhar

Reputation: 27900

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.

Upvotes: 9

Related Questions