June 4, 2014

Swift, iOS, Threading, and Grand Central Dispatch

Posted in iPhone development, mac development tagged , , , , at 5:02 pm by tetontech

This post focuses on how to use GCD in a Swift application for parallel processing. My previous post shows how to use swift with NSOperations to execute code in a background thread.

To keep things simple, I’ve put the example code in the viewDidLoad method of the view controller for the application.

override func viewDidLoad() {
        super.viewDidLoad()
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0), { ()->() in
            println("gcd hello")
            dispatch_async(dispatch_get_main_queue(), {
                println("hello from UI thread executed as dispatch")
                })
            })
        println("hello from UI thread")
    }

Notice the setting of the priority constant. If you try to use DISPATCH_QUEUE_PRIORITY_DEFAULT in the call to dispatch_get_global_queue you will get a runtime error (error #45). It appears this may be due to DISPATCH_QUEUE_PRIORITY_DEFAULT being an NSNumber and Swift wants it to be some other type and isn’t interpolating and boxing/unboxing the value. If you set the priority constant the error goes away.

Also notice that in the closure being sent to the main queue I’ve left out the ‘()->() in’ portion of the closure. It isn’t required. Swift can infer this. You could leave it out of the closure sent to the global queue too. I did it both ways for example purposes only since Swift is so new.

Advertisements

1 Comment »

  1. dineshramitc said,

    Reblogged this on Dinesh Ram Kali..


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: