dispatch_after() with zero pop time
grand-central-dispatch, ios
Solution
`dispatch_async` on the main queue will also queue the code to run on the next runloop, giving time for the system to update the UI. You can check like so:
void (^block)() = ^{
[self.tableView reloadData];
};
if (delayInSeconds) {
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), block);
}else if([NSThread isMainThread]) {
block();
}
else {
dispatch_async(dispatch_get_main_queue(), block);
}
Problem
Is it possible to make this "clearer" or "better" ? Any solution is welcome, even thought i got a right answer. The problem is dispatch_after() with popTime==0 is still giving time to the main thread to make some UI changes. The following code is sometimes called from a background thread. ``` -(void)methodCalledFromSomeThread{ if (delayInSeconds) { dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC); dispatch_after(popTime, dispatch_get_main_queue(), ^(void){ // Updating some UI like }); }else{ dispatch_async(dispatch_get_main_queue(), ^{ // Updating some UI like }); } } ```