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

前端 未结 7 1951
长情又很酷
长情又很酷 2020-12-23 15:28

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 exec

7条回答
  •  攒了一身酷
    2020-12-23 16:08

    Several technical ways to synchronize multi-threads, such as NSConditionLock(mutex-lock), NSCondition(semaphore)。But they are common programming knowledge for other languages(java...) besides objective-c. I prefer to introduce run loop(special in Cocoa) to implement thread join:

    NSThread *A; //global
    A = [[NSThread alloc] initWithTarget:self selector:@selector(runA) object:nil]; //create thread A
    [A start];
    
    - (void)runA    
    {
      [NSThread detachNewThreadSelector:@selector(runB) toTarget:self withObject:nil]; //create thread B    
      while (1)    
      {    
        if ([[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]) //join here, waiting for thread B    
        {    
          NSLog(@"thread B quit...");    
          break;    
        }    
      }    
    }
    
    - (void)runB    
    {    
      sleep(1);    
      [self performSelector:@selector(setData) onThread:A withObject:nil waitUntilDone:YES modes:@[NSDefaultRunLoopMode]];    
    }
    

提交回复
热议问题