在Objective-C中执行阻塞函数调用

时间:2019-04-12 17:37:42

标签: objective-c asynchronous

说我有一些必须执行一些异步操作的功能;顺序是这样的:

-(void) f1 {
    //1. invoke some asynchronous operation 

    //2. wait until asynchronous operation ends and invokes some delegate method 

    //3. let delegate method end

    //4. exit function
}

使用GCD队列(串行或并发)调用该函数。

约束:无法使用通知;步骤必须严格按照该顺序进行;不应使用NSOperation;

如何实现阻塞部分(序列中的第2个)?

1 个答案:

答案 0 :(得分:2)

您可能可以使用GCD Semaphores

@interface MyClass
@property (strong) dispatch_semaphore_t semaphore;
@end

@implementation MyClass

- (instancetype)init
{
    self = [super init];
    if (self) {
        _sempahore = dispatch_semaphore_create(0);
    }
    return self;

}

- (void)blockingMethod
{
    // let's assume someThing somehow already exists :)
    someThing.delegate = self;
    [someThing doAsyncStuff]; // will call someThingDelegateCallback when done

    dispatch_semaphore_wait(self.semaphore, DISPATCH_TIME_FOREVER);
}

- (void)someThingDelegateCallback
{
    dispatch_semaphore_signal(self.semaphore);
}

@end