iOS 转换异步block为同步方式运行

使用dispatch_semaphore_t

实现 dispatch_semaphore_t sema = dispatch_semaphore_create(0);

//创建信号量

__block ALAssetsGroup *ret = nil; ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) { ret = group; dispatch_semaphore_signal(sema); //关键点,在此发送信号量 };

 ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) { ret = nil; dispatch_semaphore_signal(sema); //关键点,失败时发送 };

NSUInteger groupTypes = ALAssetsGroupSavedPhotos;

[self.assetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:listGroupBlock failureBlock:failureBlock];

dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER); //关键点,在此等待信号量 return ret;

你可能感兴趣的:(iOS 转换异步block为同步方式运行)