These are personal notes from Lecture 10 of Paul Hegarty’s excellent iPhone App Dev course. Go there for the full monty on GCD you will want to go there.

What is Grand Central Dispatch.

Is a C API.
Basic idea is you have queues of operations.
Operations are specificed using blocks.
Most queues run serially (a true queue).

The operations are going to be pulled off the queue and run in some other thread.

There is no guarantee about where and when is will happen.
Good thing is that if your operation blocks, only that queue will block.
Other queues (like the main UI queue) will continue to run.

So we are going to queue up blocks things that take a long time to run in other threads, and from those threads we’ll queue up blocks back on the main ui thread to update the ui.

Example assume we fetched an image from the network:

-(void)viewWillAppear:(BOOL) animated
{
   NSData *imageData = [NSData dataWithContentsOfURL:networkURL]; // long time!
   UIImage *image = [UIImage imageWithData:imageData];
   self.imageView.image = image;
   self.imageView.frame = CGRectMake(0,0, image.size.width, image.size.height);
   self.scrollView.contentSize = image.size;
}

We don’t want the fetching of that image happening on the main queue. UI will be non-responsive.

And any rendering of the main ui, needs to be done on the main ui thread.

So we are going to need x2 queues.
One to do the long work of getting the image.
Another to update the UI.

-(void)viewWillAppear:(BOOL) animated
{

   dispatch_queue_t downloadQueue = dispatch_queue_create(“image loader”, NULL);
   dispatch_async(downloadQueue, ^{	
      NSData *imageData = [NSData dataWithContentsOfURL:networkURL]; // long time!
      dispatch_async(dispatch_get_main_queue(), ^ {
         UIImage *image = [UIImage imageWithData:imageData];
         self.imageView.image = image;
         self.imageView.frame = CGRectMake(0,0, image.size.width, image.size.height);
         self.scrollView.contentSize = image.size;
      });
   });
   dispatch_release(downloadQueue);
}

This is the power of GCD. You can think linearly about your program right in time. Run times linear here.