当按下按钮时,下面的代码就会执行。并在控制台中打印出来。
3
2
当前患者 ID:2
新患者 ID:3
你可以明显地看到 generateID()
在 print("2.\(patient.id)")
之前被触发,因此它应该在控制台中打印如下:
- 3
当前患者 ID:2
新患者 ID:3
- 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/