How to wait for a thread to finish in Objective-C

2019-01-31 01:58发布

I'm trying to use a method from a class I downloaded somewhere. The method executes in the background while program execution continues. I do not want to allow program execution to continue until this method finishes. How do I do that?

7条回答
\"骚年 ilove
2楼-- · 2019-01-31 02:59

My technique is to check if the task can run (if the background thread is finished), and if it can't run then I use GCD to try again after a delay:

- (void)doSomething
{
  if (/* is the other thread done yet? */) {
    double delayInSeconds = 2.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
      [self doSomething];
    });
    return;
  }

  // do something
}
查看更多
登录 后发表回答