+1 vote
in FuelPHP by
Find the bug in the Objective-C code below. Explain your answer?

1 Answer

0 votes
by
@interface HelloWorldController : UIViewController  

@property (strong, nonatomic) UILabel *alert;  

@end  

@implementation HelloWorldController  

- (void)viewDidLoad {
     CGRect frame = CGRectMake(150, 150, 150, 50);
     self.alert = [[UILabel alloc] initWithFrame:frame];
     self.alert.text = @"Hello...";
     [self.view addSubview:self.alert];
      dispatch_async(
        dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
        ^{
           sleep(10);
           self.alert.text = @"World";
        }
    ); 
}  

@end
Answer

All UI updates must be performed in the main thread. The global dispatch queue does not guarantee that the alert text will be displayed on the UI. As a best practice, it is necessary to specify any updates to the UI occur on the main thread, as in the fixed code below:

dispatch_async(        
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
    ^{
      sleep(10);
      dispatch_async(dispatch_get_main_queue(), ^{
         self.alert.text = @"World";
      });
});
...