Search code examples
iosobjective-cobjective-c-blocksgrand-central-dispatchdispatch-async

Why does GCD make this code work correctly?


I'm learning Objective-C and am trying to understand GCD better. I've created an object (APICaller) that makes API calls, then provides information to its delegate. In this object's delegate's (TableViewControllerA) viewDidLoad method, I call one of APICaller's methods, then use the information to update the detailTextLabel.text of two static cells. My question: Why, when I use dispatch_async, does the detailTextLabel.text update so much more quickly than without it?

This updates the cell, but with a long delay:

- (void)viewDidLoad
{
  APICaller *apiCaller = [APICaller alloc] init];

  [apiCaller getInformationWithArgument:self.argument completionHandler:^(NSString  *results, NSError *error) {
    _staticCell.detailTextLabel.text = results;
  }

}

...while this updates the cell instantly:

- (void)viewDidLoad
{
  APICaller *apiCaller = [APICaller alloc] init];

  [apiCaller getInformationWithArgument:self.argument completionHandler:^(NSString  *results, NSError *error) {
    dispatch_async(dispatch_get_main_queue, ^(void) {
           _staticCell.detailTextLabel.text = results;
      });
  }

}

Solution

  • The completion handler shown in the first code snippet is not being run on the main thread, and therefore is getting updated whenever the system decides an update is needed. The second snippet is using GCD to explicitly run the on the main thread and therefore is updated immediately.