【问题标题】:Dispatch Group notify placement?调度组通知安置?
【发布时间】:2017-02-01 22:03:13
【问题描述】:

我一直在搞乱调度组,想知道调度组的通知回调的位置如何影响回调何时被调用。我正在从我的数据库中读取数据,然后为读取的数据中的每个项目获取一张图片。当我在初始数据库读取块之外有通知时,我注意到它会立即被调用,但是当通知在块内时,它会以正确的方式运行。这是我的代码:

override func viewDidAppear(_ animated: Bool) {
        let ref = FIRDatabase.database().reference().child("users").child((FIRAuth.auth()?.currentUser?.uid)!).child("invites")
        ref.observeSingleEvent(of: .value, with: { snapshot in
            if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {
                for child in snapshots {
                    self.dispatchGroup.enter()
                    let info = petInfo(petName: child.value! as! String, dbName: child.key)
                    print(info)
                    self.invitesData[info] = UIImage()
                    let picRef = FIRStorage.storage().reference().child("profile_images").child(info.dbName+".png")
                    picRef.data(withMaxSize: 1024 * 1024) { (data, error) -> Void in
                        if error != nil {
                            print(error?.localizedDescription ?? "Error getting picture")
                        }
                        // Create a UIImage, add it to the array
                        self.invitesData[info] = UIImage(data: data!)!
                        self.dispatchGroup.leave()
                    }
                }
                self.dispatchGroup.notify(queue: DispatchQueue.main, execute: {
                    print("YOOO")
                    self.invitesArray = Array(self.invitesData.keys)
                    print(self.invitesArray)
                    self.inviteTable.reloadData()
                })
            }
        })
    }

当通知在原始数据库读取块内时,此代码会正常运行。但是,如果我将它放在 ref.observeSingleEvent 块之后,则会立即调用通知。

谁能给我解释一下?

【问题讨论】:

  • 如果你把它放在块之外,那么在你对self.dispatchGroup.enter()的任何调用到达之前就会到达通知。

标签: ios swift firebase swift3 grand-central-dispatch


【解决方案1】:

是的。异步代码:-)

代码执行一直运行到函数结束,然后将调用完成处理程序

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-19
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2013-12-20
    相关资源
    最近更新 更多