How to wrap an asynchronous method that takes a block and turn it synchronous in Objective-C

后端 未结 4 994
感情败类
感情败类 2021-02-02 18:03

I want to wrap an async API that look like this:

[someObject completeTaskWithCompletionHandler:^(NSString *result) {

}];

into a synchronous m

4条回答
  •  旧时难觅i
    2021-02-02 18:16

    I think the better solution will be NSRunLoop as given below. It's simple and working fine.

    - (NSString *)getValue {
    
        __block BOOL _completed = NO;
        __block NSString *mValue = nil;
    
        [self doSomethingWithCompletionHandler:^(id __nullable value, NSError * __nullable error) {
            mValue = value;
            _completed = YES;
        }];
    
        while (!_completed) {
            [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
        }
    
        return mValue;
    }
    

提交回复
热议问题