Problem with GCD and local UI refresh
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开发者_如何学Python 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?
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.
精彩评论