我正在尝试在swift中创建一个线程并发送两个参数。我创建线程并且这项工作:
let thread = NSThread(target:self, selector:"getData", object:nil)
thread.start()
但是如何将参数发送到我的func getData?如何使用如下参数创建对象:
let params =...
let thread = NSThread(target:self, selector:"getData", object:params)
thread.start()
...
getData(username: String, password: String) {
...
}
答案 0 :(得分:10)
您应该使用Grand Central Dispatch而不是直接使用线程。在这种情况下,您希望使用dispatch_async
在后台队列上调用getData
:
let username = ...
let password = ...
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
getData(username, password);
}
请注意,如果getData
实际上是return
个数据,那么您必须处理dispatch_async
内部的关闭:
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 !! */
如果您要在iOS上进行多线程/并发编程,我高度建议您查看Apple的Concurrency Programming Guide。
答案 1 :(得分:3)
创建一个类来保存参数怎么样?
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) {
// ...
}
答案 2 :(得分:1)
使用Swift 5更新
Thread.detachNewThreadSelector(#selector(getData), toTarget: self, with: params)
func getData(params: Params) {
// ...
}