繁体   English   中英

如何在Swift中完成另一个代码后才能运行一个代码

[英]How to make one code run only after the other is done in Swift

我是异步和同步机制的新手。 在我的代码中,我必须在另一个完成后执行一个代码行。 它看起来像这样:

    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
      }

    }
}

你的专业想法请..

你应该DispatchGroup 通过使用DispatchGroup一个函数/代码行将等待,直到另一个函数完成执行。

例如

let myGroup = DispatchGroup()
   myGroup.enter()
   let info = getInfoFromTheWeb()

当您从简单的电话获得info

myGroup.leave()

当您调用leave()函数时,将执行以下代码

myGroup.notify(queue: DispatchQueue.main) {

            saveToDB(info: info)
           /// Update UI elements
        }

尝试这样的事情:

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
            }
        }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM