June 30, 2014

Swift, NSOperationQueues, Closures, and Threading

Posted in iPhone development, mac development tagged , , , at 3:49 pm by tetontech

In a previous posting I showed how to inherit from NSOperation to do work in background processes using NSOperationQueues. In another, I showed how to use Grand Central Dispatch, GCD, to do threading. In this post I’ll give a simple example of using NSOperationQueues without NSOperations.

For this example I created a single view application, added a label to the view using Interface Builder, and added an IBOutlet for the label called ‘theLabel’ to the ViewController for the view. theLabel can only be updated by the main application thread. This means that inside the code running in the background there must be a a call that runs code in the main application thread.

To take advantage of Swift’s closures, this example uses the NSOperationQueue method called ‘addOperationWithBlock.’ Blocks are the Objective-C equivalent to Swift’s closures. Line’s 2 and 4 show the addOperationWithBlock method being used.

Line 2 adds a closure to a background queue that was created on line 1. The code in the closure will be run on a background thread. Line 4 adds a closure to the main thread’s queue for execution. Line 4 does this by taking advantage of the NSOperationQueue class method ‘mainQueue.’ mainQueue returns the queue for the application’s main thread. This means that anything in the closure defined on lines 4 – 6 will execute in the application’s main thread.

1       var backgroundQueue = NSOperationQueue()
2       backgroundQueue.addOperationWithBlock(){
3           println("hello from background")
4           NSOperationQueue.mainQueue().addOperationWithBlock(){
5               self.theLabel.text = "updated from main thread"
6           }
7       }

By creating a closure within a closure you can execute code in a background thread and after it has completed you can execute code in the main or ‘UI’ thread. You can also use if statements to update the UI in different ways depending on what happens in the background thread.

 

Advertisements

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: