DispatchQueue.main.async
{
/*Write your thread code here*/
}
53
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT) //Swift 2 version
let concurrentQueue = DispatchQueue(label:"com.swift3.imageQueue", attributes: .concurrent) //Swift 3 version
我在Xcode 8,Swift 3中重新编写了代码,并且更改标记为与Swift 2版本形成对比 .
-3
DispatchQueue.main.async {
self.collectionView?.reloadData() // Depends if you were populating a collection view or table view
}
OperationQueue.main.addOperation {
self.lblGenre.text = self.movGenre
}
@IBAction func tap(_ sender: AnyObject) {
let thisEmail = "emailaddress.com"
let thisPassword = "myPassword"
DispatchQueue.global(qos: .background).async {
// Validate user input
let result = self.validate(thisEmail, password: thisPassword)
// Go back to the main thread to update the UI
DispatchQueue.main.async {
if !result
{
self.displayFailureAlert()
}
}
}
}
14 回答
串行队列:
并发队列:
对于Swift 3
它现在简单地说:
默认为serial,要获得并发,请使用可选属性参数.concurrent
您可以在swift 3.0中使用此代码创建调度队列
我这样做了,如果您想刷新UI以显示新数据而没有用户注意到UITableView或UIPickerView,这一点尤其重要 .
我在Xcode 8,Swift 3中重新编写了代码,并且更改标记为与Swift 2版本形成对比 .
//如果需要在viewcontroller上填充对象(labels,imageview,textview),请使用Operation Queue
斯威夫特3
你想在swift代码中调用一些闭包然后你想在故事板中更改ya任何类型的更改属于视图你的应用程序将崩溃
但是你想使用调度方法你的应用程序不会崩溃
异步方法
同步方法
创建并发队列
创建一个串行队列
异步获取主队列
同步获取主队列
获得一个后台线程
Xcode 8.2 beta 2:
获得一个后台线程
如果您想了解如何使用这些队列 . 请参阅answer
在 Swift 3 下编译 . 此示例包含我们需要的大部分语法 .
QoS - 新的服务质量语法
weak self
- 中断保留周期如果自己不可用,什么也不做
async global background queue
- 用于网络查询async main queue
- 用于触摸UI .当然,您需要为此添加一些错误检查...
编译于XCode 8,Swift 3 https://github.com/rpthomas/Jedisware
由于上面已经回答了OP问题,我只想添加一些速度考虑因素:
在DispatchQueue.global中为异步函数指定的优先级等级会有很大的不同 .
我不建议使用.background线程优先级运行任务,尤其是在iPhone X上,其中任务似乎分配在低功耗内核上 .
以下是来自计算密集型函数的一些实际数据,这些函数从XML文件读取(带缓冲)并执行数据插值:
设备名称/ .background / .utility / .default / .userInitiated / .userInteractive
iPhone X:18.7s / 6.3s / 1.8s / 1.8s / 1.8s
iPhone 7:4.6s / 3.1s / 3.0s / 2.8s / 2.6s
iPhone 5s:7.3s / 6.1s / 4.0s / 4.0s / 3.8s
请注意,所有设备的数据集都不相同 . 它是iPhone X上最大的,也是iPhone 5s上最小的 .