Objective-c / iOS: setting status text in async function is slow

In my application, I am making some connection with a remote server, and since this might be slow, I thought it would be nice to run this code asynchronously. I have a communication code in a block that I pass dispatch_async. This code performs the link, and when it is done, it sets the label text. This last part is the problem. The text is set, but this occurs after a delay of several seconds. This is my code.

- (void)doNetworkingTask { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Slow network task goes here. // Slow network task done, notify the user. [self.myLabel setText:@"task done."]; NSLog(@"task done."); }); } 

What happens is that my network task is completed, the NSLog text is registered, and after a couple of seconds the label text is updated. My question is: 1) why the label text is not updated instantly? and 2) what is the right way to do what I want to do? (Perform a slow network task without blocking anything else, update the user through a text label as soon as you finish.)

+4
source share
1 answer

User interface updates should be in the main thread. Update your code something like this:

 - (void)doNetworkingTask { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // Slow network task goes here. // Slow network task done, notify the user. dispatch_async(dispatch_get_main_queue(), ^{ [self.myLabel setText:@"task done."]; }); NSLog(@"task done."); }); } 
+7
source

All Articles