Reply to comment

strict warning: Only variables should be passed by reference in /var/www/www.waterworld.com.hk/sites/all/modules/captcha/captcha.inc on line 61.

Convert async block to sync

Since iOS 5, many apis will only provide block version and so we will get the result in async order. Sometimes we may want to get the result immediately by scarifying the benefit of GCD.

In old style, we can't do it using 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;

that we wait for a signal at the end of the block.

For cleaner code, now we can use 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;

Reply

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can use Markdown syntax to format and style the text. Also see Markdown Extra for tables, footnotes, and more.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
6 + 1 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.