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) {
...
}
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.
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)
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.
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 return
s 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With