|
Answer» @interface MyCustomController : UIViewController @property (strong, nonatomic) UILabel *alert; @end @implementation MyCustomController - (void)viewDidLoad { CGRect FRAME = CGRectMake(100, 100, 100, 50); self.alert = [[UILabel alloc] initWithFrame:frame]; self.alert.text = @"PLEASE wait..."; [self.view addSubview:self.alert]; dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(10); self.alert.text = @"Waiting over"; } ); } @end Ans: All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue MAKES no GUARANTEES . Therefore the code should be MODIFIED to always run the UI update on the main thread dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(10); dispatch_async(dispatch_get_main_queue(), ^{ self.alert.text = @"Waiting over"; }); }); @interface MyCustomController : UIViewController @property (strong, nonatomic) UILabel *alert; @end @implementation MyCustomController - (void)viewDidLoad { CGRect frame = CGRectMake(100, 100, 100, 50); self.alert = [[UILabel alloc] initWithFrame:frame]; self.alert.text = @"Please wait..."; [self.view addSubview:self.alert]; dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(10); self.alert.text = @"Waiting over"; } ); } @end Ans: All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue makes no guarantees . Therefore the code should be modified to always run the UI update on the main thread dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ sleep(10); dispatch_async(dispatch_get_main_queue(), ^{ self.alert.text = @"Waiting over"; }); });
|