Synchronous dispatch without deadlocking

March 4, 2013 in iOS Snippets

Dispatches synchronously without deadlocking if the target thread is the current thread.

static inline void dispatch_sync2(dispatch_queue_t queue, dispatch_block_t block) {
 if (dispatch_get_current_queue() == queue) {
 } else {
 dispatch_sync(queue, block);

Running code on the UI thread

February 27, 2013 in iOS Snippets

As an iOS developer you’ll get to see this all the time, since you have to be enormously careful when running code that does any UI processing; such code must always run in the main (UI) thread, so when running on a different thread it’s necessary to pass a block of code to be executed by the main thread:

dispatch_async(dispatch_get_main_queue(), ^{

// ... code to execute in main thread ...


dispatch_async() will run that code right away, asynchronously – ie, it will not wait to queue the code into the main queue. Use dispatch_sync() if you want to wait until it’s done – but be careful! If you target the current queue, it will result in a deadlock. More information in the official documentation.