在iOS5以后较性,許多API將只提供block版本饱亮,所以調(diào)用這些API就總是以異步方式運(yùn)行的了。但有時(shí)候我們不想使用異步方式假抄,例如我們想要調(diào)用函數(shù)后立刻獲取結(jié)果值的時(shí)候。
在舊的方式中丽猬,我們無(wú)法使用NSCondition做這件事:
__block NSCondition *condition = [[NSCondition alloc] init];
__block ALAssetsGroup *ret = nil;
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
[condition lock];
ret = group;
[condition signal];
[condition unlock];
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
[condition lock];
ret = nil;
[condition signal];
[condition unlock];
};
NSUInteger groupTypes = ALAssetsGroupSavedPhotos;
[self.assetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:listGroupBlock failureBlock:failureBlock];
[condition lock];
[condition wait];
[condition unlock];
return ret;
我們?cè)赽lock的結(jié)尾處等待一個(gè)信號(hào)量宿饱。
更簡(jiǎn)單的辦法是使用dispatch_semaphore_t:
dispatch_semaphore_t sema = dispatch_semaphore_create(0);? //創(chuàng)建信號(hào)量
__block ALAssetsGroup *ret = nil;
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
ret = group;
dispatch_semaphore_signal(sema);? //關(guān)鍵點(diǎn),在此發(fā)送信號(hào)量
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
ret = nil;
dispatch_semaphore_signal(sema);? //關(guān)鍵點(diǎn)脚祟,失敗時(shí)發(fā)送
};
NSUInteger groupTypes = ALAssetsGroupSavedPhotos;
[self.assetsLibrary enumerateGroupsWithTypes:groupTypes usingBlock:listGroupBlock failureBlock:failureBlock];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);? //關(guān)鍵點(diǎn)刑棵,在此等待信號(hào)量
return ret;