Making objective-c blocks synchronous

Many IOS libraries require you to do things asynchronously. Some of the better libraries provide both asynchronous and synchronous models to work with, but some do not.

IOS’ ALAssetLibrary is a good example of a library providing only asynchronous processing. The ALAssetLibrary allows you to fetch images, videos, and the like from a user’s camera roll, and you’re required to work with things in blocks, using a forced asynchronous method. In most cases, you’ll want asynchronous processing when working with the ALAssetLibrary, but sometimes that may be overkill.

If you want to synchronously reason about a series of assets in the library, you’ll want to wrap the async block mess in something synchronous. For example, in my case, I wanted to synchronously check if asset URLS previously stored are still valid.

OmegaDelta’s How to wait for iOS methods with completion-blocks to finish shows you how to synchronously reason with ALAssetLibrary, or any other asynchronous block for that matter.

I’ve wrapped OmegaDelta’s example into a utility method that suits my specific use case in a utility called AssetURLChecker.

View or Download the AssetURLChecker utility code.

You can use this example code to easily wrap any asynchronous call into something synchronous, for simplified reasoning.

Careful though, synchronous code will not be as performant as asynchronous code, be sure you know what trade-off you’re making for your simplification.