Ios 如何使一个代码仅在另一个代码在Swift中完成后运行
我不熟悉异步和同步机制。 在我的代码中,我必须在完成另一行代码之后才执行一行代码。 它看起来像这样:Ios 如何使一个代码仅在另一个代码在Swift中完成后运行,ios,swift,concurrency,synchronization,Ios,Swift,Concurrency,Synchronization,我不熟悉异步和同步机制。 在我的代码中,我必须在完成另一行代码之后才执行一行代码。 它看起来像这样: func something(){ let workerQueue = DispatchQueue.global(qos: .userInitiated) workerQueue.async{ let info = getInfoFromTheWeb()//I need the info value in order to perfor
func something(){
let workerQueue = DispatchQueue.global(qos: .userInitiated)
workerQueue.async{
let info = getInfoFromTheWeb()//I need the info value in order to perform the next line
saveToDB(info: info)
DispatchQueue.main.async {
//update a label text in the ui after getting and saving that info
}
}
}
func something() {
let workerQueue = DispatchQueue.global(qos: .userInitiated)
workerQueue.async{
if let info = getInfoFromTheWeb() {
saveToDB(info: info)
DispatchQueue.main.async {
//update a label text in the ui after getting and saving that info
}
}
}
您的专业想法请….试试这样:
func something(){
let workerQueue = DispatchQueue.global(qos: .userInitiated)
workerQueue.async{
let info = getInfoFromTheWeb()//I need the info value in order to perform the next line
saveToDB(info: info)
DispatchQueue.main.async {
//update a label text in the ui after getting and saving that info
}
}
}
func something() {
let workerQueue = DispatchQueue.global(qos: .userInitiated)
workerQueue.async{
if let info = getInfoFromTheWeb() {
saveToDB(info: info)
DispatchQueue.main.async {
//update a label text in the ui after getting and saving that info
}
}
}
您应该
调度组
。通过使用DispatchGroup
一个函数/代码行将等待另一个函数完成执行
比如说
let myGroup = DispatchGroup()
myGroup.enter()
let info = getInfoFromTheWeb()
当您通过简单的呼叫获得信息时
myGroup.leave()
当您调用leave()
函数时,将执行以下代码
myGroup.notify(queue: DispatchQueue.main) {
saveToDB(info: info)
/// Update UI elements
}
只需回顾一下GCD的概念及其工作原理。您自己肯定会找到答案:)行一行接一行地执行,问题是什么?getInfoFromTheWeb
async吗?看起来不像,您已经在一个单独的线程上,可以执行同步请求。这意味着当到达saveToDB
时,web信息已经存在。我认为您的概念/问题与使用完成处理程序有关,这是一个很好的教程!您需要使用dispatch\u sync,而不是dispatch\u async。同步和异步执行每个工作项可以同步或异步执行。当工作项与sync方法同步执行时,程序将等待执行完成,然后方法调用返回。当使用async方法异步执行工作项时,方法调用立即返回@在这种情况下,我需要的信息有价值的。你的建议不行,谢谢你,鲍比。如果没有呢?info=getInfoFromTheWeb()。那么saveToDB()就不会执行了?没错,如果info为nil,那么如果需要执行某些任务,可以使用Else语句。Usman,iOS中的默认值是以异步方式运行代码吗@乌斯曼·贾维德耶,关于更多细节,我建议您详细阅读DispatchGroup。