Tag Archives: Blocks

How to execute a method on another thread using Grand Central Dispatch

Everything in your iOS app happens on “the main thread” by default. It’s like at the hairdresser’s – one thing after another. Since iOS 4 however you can execute things “asynchronously” by using Grand Central Dispatch. With it comes another phenomenon called Blocks.

To make use of this feature you need to

  • define your own dispatch queue (dispatch_queue_t)
  • create your own dispatch queue (giving it a reverse DNS identifier)
  • wrap what you want to execute inside block

The syntax for this looks a bit odd and not like Objective-C, because those are “classic” C statements. As for Blocks: think of them as an anonymous function call. They allow you to specify how the background queue should react after the execution of your method has finished on the other thread.

Let’s see how this works. First define the queue, just under all those import statements will work fine:

When you’re ready to use it, give it an identifier and add an execution block:

The identifier will show up in log messages and Instruments if applicable. The block is executed at the end of the operation, on your “specialQueue”. It’s a great place to asses success or failure.

Note that UI Elements can only be updated from the main thread, so don’t change any labels from that “specialQueue”. You can however dispatch things specifically from the main queue while in your own queue:

Here we switch off the network indicator while we’re in our own queue, by dispatching this statement on the main queue.

How to create a Save As dialogue with NSSavePanel

Likewise we can save our previously selected file using an NSSavePanel. It too is easy to use, just as the NSOpenPanel.

For a save action to make sense we need to have some data to save, so in this example we will copy an existing file (self.myURL) to the new URL that the save panel returns. We’ll let the NSFileManager just create a copy with a new name that the user specifies using the save panel:

The only alien looking thing here is the use of a Block (like it is in the NSOpenPanel). This is the equivalent to an anonymous function in JavaScript, basically a block of code that runs upon completion. As it’s part of the method call, the closing ] is way at the bottom.

Further Reading

Apple’s NSSavePanel Class Reference:

A Short Practical Guide to Blocks: