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

前端 未结 7 1949
长情又很酷
长情又很酷 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:09

    For such cases I usually using NSCondition class.

    //this method executes in main thread/queue
    - (void)waitForJob
    {
        id __weak selfWeak = self;
        NSCondition *waitHandle = [NSCondition new];
        [waitHandle lock];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
            [selfWeak doSomethingLongtime];
            [waitHandle signal];
        });
        //waiting for background thread finished
        [waitHandle waitUntilDate:[NSDate dateWithTimeIntervalSinceNow:60]];
    }
    

提交回复
热议问题