Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dispatch_after() with zero pop time

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
        });
    }
}
like image 280
Laszlo Avatar asked Mar 03 '26 09:03

Laszlo


1 Answers

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);
}
like image 62
Léo Natan Avatar answered Mar 05 '26 23:03

Léo Natan