【问题标题】:Confused about async block inside loop对循环内的异步块感到困惑
【发布时间】:2021-07-26 14:56:54
【问题描述】:

我只想在闭包块内执行完所有循环后打印数据,因为我不知道如何准确地使用调度组。我尝试了多种方式。

我在这里做错了什么?

private func recognizeText(images: [UIImage]) {
    
    let myDispatchGroup = DispatchGroup()
    
    self.extractedTextfromImages(images: images) { blocks in
        myDispatchGroup.enter()
        
        for block in blocks {
            
            for line in block.lines {
                
                
                //save emirate id
                if isValidEmiratesID(emiratesID: line.text) == true {
                    
                    let id  = line.text
                    self.dt.id = id
                }
                
                // save name
                if line.text.lowercased().range(of: "name") != nil {
                    
                    
                    if let range = line.text.range(of: ":") {
                        let nm = line.text[range.upperBound...]
                        let name = String(nm.trimmingCharacters(in: .whitespaces))
                        self.dt.name = name
                    }
                }
                
            }
            
        }
        myDispatchGroup.leave()
    }
    
    myDispatchGroup.notify(queue: .main) {
        print("data is \(self.dt)")
    }
    
    
    
}

【问题讨论】:

  • 我认为在此之前myDispatchGroup.leave() 你可以打印。
  • 你的地方可以重写我的代码并作为答案发布吗????
  • DispatchGroup单个异步任务的上下文中毫无意义。

标签: swift swift3 swift4 swift5


【解决方案1】:
myDispatchGroup.enter()
              
        for i in 1...3 {
            
         print("out")
            for i in 1...3 {       
                     print("inner")   
                           } 
                       }
                myDispatchGroup.leave()
            
            
            myDispatchGroup.notify(queue: .main) {
                print(“now loop ended ")
            
    }

输出 =

出来

内部

内部

内部

出来

内部

内部

内部

出来

内部

内部

内部

现在循环结束

【讨论】:

    猜你喜欢
    • 2018-10-03
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    • 2023-01-13
    • 2020-10-23
    相关资源
    最近更新 更多