在Swift 2中,我能够用以下代码创建队列:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
但是这不能在Swift 3中编译。
在Swift 3中,首选的方式是什么?
在Swift 2中,我能够用以下代码创建队列:
let concurrentQueue = dispatch_queue_create("com.swift3.imageQueue", DISPATCH_QUEUE_CONCURRENT)
但是这不能在Swift 3中编译。
在Swift 3中,首选的方式是什么?
当前回答
斯威夫特3
你想在swift代码中调用一些闭包然后你想在storyboard中改变任何类型的改变属于视图,你的应用程序会崩溃
但是你要使用分派方法,你的应用程序不会崩溃
异步方法
DispatchQueue.main.async
{
//Write code here
}
同步方法
DispatchQueue.main.sync
{
//Write code here
}
其他回答
由于OP问题已经在上面得到了回答,我只想添加一些速度方面的考虑:
在DispatchQueue.global中为async函数分配的优先级类有很大不同。
我不建议使用.background线程优先级运行任务,尤其是在iPhone X上,因为任务似乎是分配在低功耗内核上的。
下面是一个计算密集型函数的一些真实数据,该函数从XML文件中读取(带缓冲)并执行数据插值:
设备名/ .background / .utility / .default / .userInitiated / .userInteractive
iPhone X: 18.7s / 6.3s / 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最小。
在XCode 8编译,Swift 3 https://github.com/rpthomas/Jedisware
@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()
}
}
}
}
创建并发队列
let concurrentQueue = DispatchQueue(label: "queuename", attributes: .concurrent)
concurrentQueue.sync {
}
创建一个串行队列
let serialQueue = DispatchQueue(label: "queuename")
serialQueue.sync {
}
异步获取主队列
DispatchQueue.main.async {
}
同步获取主队列
DispatchQueue.main.sync {
}
获取一个背景线程
DispatchQueue.global(qos: .background).async {
}
Xcode 8.2 beta 2:
获取一个背景线程
DispatchQueue.global(qos: .default).async {
}
DispatchQueue.global().async {
// qos' default value is ´DispatchQoS.QoSClass.default`
}
如果你想了解如何使用这些队列。请看这个答案
我这样做了,如果你想在不被用户注意的情况下刷新你的UI来显示新数据,比如UITableView或UIPickerView,这就特别重要。
DispatchQueue.main.async
{
/*Write your thread code here*/
}
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
}
//使用操作队列如果你需要填充对象(标签,imageview, textview)在你的视图控制器