How to wait in NSThread until some event occur in iOS?

前端 未结 3 1040
野性不改
野性不改 2021-02-14 10:10

How to wait inside the NSThread until some event occur in iOS?

eg, We created a NSThread and started a thread loop. Inside the thread loop, there is condition to check w

3条回答
  •  攒了一身酷
    2021-02-14 10:53

    You can use a semaphore. See the example below, the logic is pretty simply. Im my example, the blocks are executed in background, and my main thread waits for the dispatch signal of the semaphore to go on. The main difference is in my case the thread waiting is the main thread, but the semaphore logic is here, I think you can easily adapt this to your case.

    //create the semaphore
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
    
    [objectManager.HTTPClient deletePath:[address addressURL] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    
          //some code here
    
            dispatch_semaphore_signal(semaphore);
    
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
           //some other code here
    
            dispatch_semaphore_signal(semaphore);
        }];
    
    //holds the thread until the dispatch_semaphore_signal(semaphore); is send
    while (dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
    {
        [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:10]];
    }
    

提交回复
热议问题