0

i am new to Objective C, i have one question regarding dispatch. Does anyone know why the block added to the queue is not run?

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        dispatch_async(dispatch_get_main_queue(), ^{        
            NSLog(@"hello world");   
        });    
    };

    return 0;
}
Rob
  • 415,655
  • 72
  • 787
  • 1,044
Anson
  • 1
  • 1

1 Answers1

0

Your program is exiting before the asynchronously dispatched block had a chance to execute. This code is basically saying “dispatch this log statement to run when the main thread for this program is free”, but is also effectively saying “dispatch that block of code run asynchronously (i.e. later) but then immediately exit”. As you can imagine, it’s just exiting before it gets around to being able to execute that dispatched block.

This pattern of dispatching code to run asynchronously makes most sense when you’re writing a full-fledged “app” (with UI where the user can do stuff and quit the app at a time of their choosing), rather than a “command line tool”. If you do this in an app, you will see your NSLog statement. So, when creating your test project, create an “app” rather than a “command line tool”. Then you’ll see your log statement fine.

This notion of dispatching code to run asynchronously (esp when you dispatch that to the main queue) doesn’t quite make sense for most command line tools. Theoretically you could create your own “run loop” to keep the command line tool alive until your dispatched block has a chance to run, but that’s not a very common pattern. Most command line tools just do something and then exit, and don’t have asynchronous blocks running.

If there’s some reason you feel like you really want to do this in a command line app, please edit your question to describe your scenario in greater detail. If you are just experimenting with GCD, it’s just simpler to do this with an “app” rather than a “command line tool”.

Rob
  • 415,655
  • 72
  • 787
  • 1,044