Search code examples
iphoneobjective-cgrand-central-dispatchthread-sleep

Objective -c: Need some explanation on the following code regarding dispatch_async (GCD)


Basically the code below works as follows, when I push a button it causes both labels to update in 4 seconds with its respected text at same time. However, if I comment out dispatch_async(dispatch_get_main_queue(), ^(void){ my labels still update but it will take first label 4 second then the second label updates 4 seconds later after the first label. I am wondering if someone can explain why both labels update in 4 seconds with the dispatch code in a dumb down matter so to speak. I try listening to the tutorial explanation, but it just confused me even more.

void (^tFunct1)(UILabel *,NSString*) = ^(UILabel *lbl, NSString *src){
 NSLog(@"GO TO SLEEP...");
 sleep(4);
 NSLog(@"WAKING UP...");
dispatch_async(dispatch_get_main_queue(), ^(void){
[lbl setText:src];
NSLog(@"Label Done!");
});

};
 -(IBAction)buttonPressed:(id)sender{
aConCurrentQue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(aConCurrentQue ,^{ tFunct1(self ->lblOne, @"1 GO!" ); } );
dispatch_async(aConCurrentQue ,^{ tFunct1(self ->lblTwo, @"2 GO!" ); } );
 }

Solution

  • You always must do UI updates on the main queue. By commenting out the dispatch to the main queue, you're trying to do UI updates on a background global queue, which explains the incorrect behavior.

    UIKit is not designed (with a few very specific exceptions) to work on the background queue and you simply should not be updating the UI on a background queue.