swift - Firebase 数据库,为什么之前打印 firebase 代码之后的打印行?

标签 swift firebase-realtime-database

当按下按钮时,下面的代码就会执行。并在控制台中打印出来。

  1. 3

  2. 2

当前患者 ID:2

新患者 ID:3

你可以明显地看到 generateID()print("2.\(patient.id)") 之前被触发,因此它应该在控制台中打印如下:

  1. 3

当前患者 ID:2

新患者 ID:3

  1. 3

怎么了? 我是新手,感谢任何帮助。

@IBAction func buttonPressed(_ sender: UIButton) {
    let patientDatabaseReference = Database.database().reference().child("Patients")

    print("1. \(patient.id)") // patient.id is naturally set to 3.

    patient.id = "2"

    patientDatabaseReference.observe(.value, with: { (snapshot) in

        for childSnap in  snapshot.children {
            guard let childSnapshot = childSnap as? DataSnapshot else {
                continue
            }

            if childSnapshot.key == self.patient.id {
                self.generateID() // I have made sure that this line gets executed.
            }

        }
    })

print("2. \(patient.id)")

}

//

func generateID() {

    let numberOfPatientsReference = Database.database().reference(withPath: "NumberOfPatients")
    numberOfPatientsReference.observeSingleEvent(of: .value, with: { snapshot in

        if !snapshot.exists() {
            return
        }

        self.patient.id = "\(snapshot.value!)"

        print("Current Patient ID: \(self.patient.id)")

        var intPatientID = Int(self.patient.id)!
        intPatientID += 1
        self.patient.id = "\(intPatientID)"

        print("New Patient ID: \(self.patient.id)")

    })
}

最佳答案

代码是异步的。这意味着当观察 block 与网络对话时,打印行将发生。如果您将 print 语句放在 observe 代码块中,它将按您期望的方式工作。

关于swift - Firebase 数据库,为什么之前打印 firebase 代码之后的打印行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48468618/

相关文章:

Swift Firebase 查询 child 的 child

swift - Cocoa:缩小主视图/细节 View ,类似 Keynote 的应用程序

java - 当 Firebase 中的值发生更改时,Sharedpreferences 值会更新

swift - 如何从 Firebase 获取特定数据

javascript - node.js:遍历嵌套的 firebase JSON 树

ios - 如何使用 Swift 通过代码库增加和减少 UIView 高度

ios - 为什么 rightRevealToggle 在 'SWRevealViewController' 中什么都不做?

android - 如何在 Firebase 中对节点的子值实现唯一约束?

javascript - 从 firebase 检索值时收到未定义的消息

swift - 在 swift 中使用 stride 的优势