gellezzz
gellezzz

Reputation: 1263

Creating threads with parameters in Swift?

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) {
    ...
}

Upvotes: 6

Views: 20251

Answers (3)

Aakash Verma
Aakash Verma

Reputation: 101

Updated with Swift 5

Thread.detachNewThreadSelector(#selector(getData), toTarget: self, with: params)
func getData(params: Params) {
    // ...
}

Upvotes: 3

Mike S
Mike S

Reputation: 42345

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.

Upvotes: 13

Grimxn
Grimxn

Reputation: 22517

What about creating a class to hold your parameters?

class Params {
    username: String
    password: String
    init (#username: String, password: String) {
        self.username = username
        self.password = password
    }
}
// ...
let thread = NSThread(target:self, selector:"getData:", object:Params(username:"xyz", password:"abc")
thread.start()
// ...
func getData(params: Params) {
    // ...
}

Upvotes: 3

Related Questions