Understanding dispatch_async

user2332873 picture user2332873 · Apr 29, 2013 · Viewed 249.8k times · Source

I have question around this code

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSData* data = [NSData dataWithContentsOfURL: 
      kLatestKivaLoansURL];
    [self performSelectorOnMainThread:@selector(fetchedData:) 
      withObject:data waitUntilDone:YES];
});

The first parameter of this code is

dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) 

Are we asking this code to perform serial tasks on global queue whose definition itself is that it returns global concurrent queue of a given priority level?

What is advantage of using dispatch_get_global_queue over the main queue?

I am confused. Could you please help me to understand this better.

Answer

David picture David · Apr 29, 2013

The main reason you use the default queue over the main queue is to run tasks in the background.

For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.

dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
    //Background Thread
    dispatch_async(dispatch_get_main_queue(), ^(void){
        //Run UI Updates
    });
});