代码之家  ›  专栏  ›  技术社区  ›  Josch Hazard

如何在异步迭代中设置DispatchGroup?

  •  0
  • Josch Hazard  · 技术社区  · 7 年前

    func download() {
    
        let logos = [Logos]()
        let group = DispatchGroup()
    
        logos.forEach { logo in
    
            print("enter")
            group.enter()
    
            if logo?.data == nil {
    
                let id = logo?.id as! String
    
                if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {
    
                    print(checkedUrl)
    
                    LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in
    
                        logo?.data = data
                        print("stored")
    
                        group.leave()
                        print("leave")
                    }
                }
            }
        }
    
        print("loop finished")
    }
    

    输出:

    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/sd.png
    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/hd.png
    loop finished
    stored
    leave
    stored
    leave
    stored
    leave
    stored
    leave
    

    看起来迭代根本不关心进入和离开DispatchGroup()。webrequests几乎同时启动。在我看来,输出应该是这样的:

    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/og.png
    stored
    leave
    enter
    http://www.apple.com/euro/ios/ios8/a/generic/images/eg.png
    stored
    leave
    ...
    loop finished
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   J. Doe    7 年前

    group.notify(queue: .main) {
    print("loop finished")
    }
    

    而不是你的正常打印。

    编辑:

    func download() {
    
    let logos = [Logos]()  // NSManagedObject
    let group = DispatchGroup()
    
    logos.forEach { logo in
    
    
        if logo?.data == nil {
            let id = logo?.id as! String
            if let checkedUrl = URL(string: "http://www.apple.com/euro/ios/ios8/a/generic/images/\(id).png") {
    
                print(checkedUrl)
                 print("enter")
                group.enter()
                LogoRequest.init().downloadImage(url: checkedUrl) { (data)  in
                    //this is async I think
    
                    coin?.logo = data
                    print("stored")
    
                    group.leave()
                    print("leave")
                }
            }
        }
    }
    
    group.notify(queue: .main) {
    print("loop finished")
    }
    }