模拟异步block:
- (NSString *)blockReturn { __block NSString *str = @"sst"; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ str = @"Sunstataa"; }); return str; }
此时返回的str = @"sst",原理大家都懂,问题是怎么实现异步return正确值。
最简单方便的方法就是使用信号量,初始化信号量为0,等待异步执行完毕再增加信号量:
- (NSString *)blockReturn { // 创建信号量 dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); __block NSString *str = @"sst"; dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ str = @"Sunstataa"; //信号量+1 dispatch_semaphore_signal(semaphore); }); //信号量等等 dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); return str; }