Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 572
MGA Avatar asked Mar 05 '12 04:03

MGA


1 Answers

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.

like image 157
David Gelhar Avatar answered Sep 17 '22 22:09

David Gelhar