美文网首页
iOS异步转同步操作

iOS异步转同步操作

作者: 扯淡的青春_ | 来源:发表于2018-07-22 22:20 被阅读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;
    }
    

    相关文章

      网友评论

          本文标题:iOS异步转同步操作

          本文链接:https://www.haomeiwen.com/subject/rtirmftx.html