iOS异步转同步操作

2018-07-22  本文已影响0人  扯淡的青春_

异步方法同步执行

1.dispatch_group

- (NSInteger)methodSyncDispatchGroup
{
    __block NSInteger result = 0;
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_enter(group);
    [self methodAsync:^(NSInteger value) {
        result = value;
        dispatch_group_leave(group);
    }];
    dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
    return result;
}

2.dispatch_semaphore

- (NSInteger)methodSyncSemaphore
{
    __block NSInteger result = 0;
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    [self methodAsync:^(NSInteger value) {
        result = value;
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    return result;
}
上一篇下一篇

猜你喜欢

热点阅读