Creating threads with parameters in Swift?

gellezzz picture gellezzz · Oct 2, 2014 · Viewed 16.5k times · Source

I am trying to create a thread in swift and send two parameters. I create thread and this work:

let thread = NSThread(target:self, selector:"getData", object:nil)
thread.start()

But how to send parameters to my func getData? How to create object with parameters like this:

let params =...
let thread = NSThread(target:self, selector:"getData", object:params)
thread.start()

...

getData(username: String, password: String) {
    ...
}

Answer

Mike S picture Mike S · Oct 2, 2014

Instead of using threads directly, you should be using Grand Central Dispatch. In this case you'd want to use dispatch_async to call getData on a background queue:

let username = ...
let password = ...

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
    getData(username, password);
}

Keep in mind that if getData actually returns data then you'll have to handle that inside dispatch_async's closure:

let username = ...
let password = ...

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
    let someData = getData(username, password)
    /* do something with someData */
}

/* !! someData is NOT available here !! */

I highly recommend taking a look at Apple's Concurrency Programming Guide if you're going to be doing multithreaded / concurrent programming on iOS.