Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {
    ...
}
like image 529
gellezzz Avatar asked Oct 02 '14 12:10

gellezzz


People also ask

How do you create a new thread in Swift?

Creating a thread in Swift is pretty simple using Thread class. You can either specify objc function through selector as a starting point, or pass a closure, and, more convenient way, subclass Thread . Thread is not started when the initializer is called. You need to call start() method explicitly to start the tread.

How many types of threads are there in Swift?

As I understand there are 3 types of DispatchQueue in swift: Main (serial) (Main Thread) Global (Concurrent) (Background Threads working in parallel) Custom (Concurrent or serial)

What is DispatchQueue in Swift?

Dispatch queues are FIFO queues to which your application can submit tasks in the form of block objects. Dispatch queues execute tasks either serially or concurrently. Work submitted to dispatch queues executes on a pool of threads managed by the system.


1 Answers

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.

like image 117
Mike S Avatar answered Sep 30 '22 11:09

Mike S