ios - 函数在完成处理程序完成之前完成它的执行

标签 ios swift macos cocoa

我想返回从 HelperConnection.shared.getInfo() 计算的结果。但我总是在结果变量中得到 nil(也在 group.wait 之后)。如何在 HelperConnection.shared.getInfo() 完成之前停止当前函数的执行?

  func install(lists:[String]) {
    let group = DispatchGroup()
    var result : String!

    if lists.count != 0 {
        for i in lists {
            group.enter()
            HelperConnection.shared.getInfo(str: i, completion: { (str) in
                if str == "1" {
                    DispatchQueue.main.async {
                        result = str
                        group.leave()
                    }
                } else {
                    DispatchQueue.main.async {
                        result = "Hello"
                        group.leave()
                    }
                }
            })
        }
    }
    print(result)
    print(".........")
    group.wait(timeout: .now() + 5)
    print(result)
    return result
   }

最佳答案

使用notify 而不是wait 并添加完成处理程序。强制异步任务同步是不好的做法。

func install(lists:[String], completion: @escaping: (String)->Void) {
    let group = DispatchGroup()
    var result = ""

    if lists.isEmpty { (completion("")) }
    for i in lists {
        group.enter()
        HelperConnection.shared.getInfo(str: i, completion: { str in
            defer(group.leave())
            if str == "1" {
               result = str
            } else {
               result = "Hello"
            }
        })
    }       

    group.notify(queue: DispatchQueue.main) {
        print(".........")
        print(result)
        completion(result)
   }
}

关于ios - 函数在完成处理程序完成之前完成它的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54288228/

相关文章:

ios - 获取另一个 UIView 下的 UIView

ios - Swift iOS - 在 View 更改后使用哪个 viewController 生命周期事件将数据发送到 Firebase

ios - Sprite Kit SKScene 集成 iAd 后尺寸错误或根本无法工作

ios - 在 Mac Catalyst 中访问 NSWindow

c++ - OSX - 用通过 Homebrew 安装的 4.9 替换 gcc 版本 4.2.1

ios - UIWebView 委托(delegate)未触发? iOS系统

ios - UITextView – 无法在文本上设置下划线或删除线属性?

ios - 单个 UIViewController 中的多个 Collection View 未调用 cellForItemAtIndexPath indexPath

ios - 通用 Swift 序列类型生成器

cocoa - CGEventTap 阻止应用程序输入