How to execute a method on a background thread in iOS

To call something from a background thread we can use dispatch_async.

This cryptic looking statement will throw something to a background thread while the main thread can deal with other functions. This is especially useful if a method would take a long time to return and would be blocking your app while it’s waiting for an answer.

When your method comes back with a result if executes a block which can be used to react to that result.

Consider this example:

This method waits for 3 seconds and then presents a random number between 0 and 99. Hook it up to a button in the Single View Template. Then add a Date Picker. Don’t hook that one up though: just spin it with all your might, and then click your button to see what happens.

The Date Picker stops rolling while your action sleeps, and continues to spin when it’s finished to present the result. Simon Allardice used this trick in his course on – well worth watching.

Now hook up another button to the following method:

This looks complicated, but thanks to Xcode’s code completion it’s easy to use wherever you need. Here’s what’s happening:

We create a background queue and execute the same function as above. When it’s done we’ll grab the main queue (or main thread) again and update our UI element. This has to be done on the main thread. If you try it on the background thread it won’t work (it won’t crash either which is good to know).

Try it out! You’ll soon be dispatching all kinds of things on a background thread!

Here’s a fully working iOS 7 Demo Project on GitHub:

I’ve written another article about this subject here:

About Jay Versluis

Jay is a medical miracle known as Super Survivor. He runs two YouTube channels, five websites and several podcast feeds. To see what else he's up to, and to support him on his mission to make the world a better place, check out his Patreon Campaign.

4 thoughts on “How to execute a method on a background thread in iOS

    1. Hi bhavesh,

      There’s a difference between concurrency and background mode. Concurrency means executing several threads at the same time, as discussed in this post.

      Background mode, or Multitasking – which I believe is what you’re asking about – is when your own app has been minimized with the home button and is no longer in the foreground.

      From the top of my head I’d say it is possible to execute something every 3 seconds when your app is in the background, but sadly I don’t know how to do it. Sorry 😉

Leave a Reply to bhavesh Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.