Reputation: 1237
I got this code
-(void)changeText
{
dispatch_queue_t gqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(gqueue, ^(void){
//simulate a network traffic delay
[NSThread sleepForTimeInterval:5];
NSLog(@"start executing");
self.mylabel.text = @"Yeah! Text Changed";
NSLog(@"stop exec");
});
}
Problem is, it take too much time to change label text than normally do. If I use main queue, it will do instantly but UI will be blocked for 5 seconds.
What is the proper way to use GCD so that I can download stuff in another thread, my UI will not be blocked, and as soon as my work done, my UI will change instantly?
Upvotes: 2
Views: 1292
Reputation: 299585
You cannot modify UIKit objects (such as UILabel
) on a background thread. The above should be:
-(void)changeText
{
dispatch_queue_t gqueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(gqueue, ^(void){
//simulate a network traffic delay
[NSThread sleepForTimeInterval:5];
NSLog(@"start executing");
dispatch_async(dispatch_get_main_queue(), ^{
self.mylabel.text = @"Yeah! Text Changed"; });
NSLog(@"stop exec");
});
}
You can also use dispatch_sync
rather than display_async
to wait for the main thread to process the change, but be careful of deadlock.
Upvotes: 5