由于某种原因,从Firebase检索数据后,数据确实检索成功。
func retrieveData(user: User) {
//let userID = Auth.auth().currentUser?.uid
let email = user.emailAddress!
// print(email)
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Get user value
print("whats up ")
if let value = snapshot.value as? [String:String] {
let res = value["posts"]
user.deserialize(data: res!)
if( user === self.u1) {
print("they are same obj") // this will print, so they are pointing to the same address
}
print(self.u1.posts) // this also printed the things I want
}
// ...
})
if( user === self.u1) {
print("they are same obj outside") // this also prints
}
print(self.u1.posts) // but once they exist closure, this one just become empty, as as user.posts
}
我真的不明白这里发生了什么。好像数据只是在关闭后正确存储了。另外,我不知道为什么闭包外的代码先打印。非常感谢您的帮助!
这是运行结果
它们在外面是相同的obj [:]
怎么了 他们是相同的对象 [“ a @ hotmail 0”:RadiUs.Post]
答案 0 :(得分:0)
由于异步操作,您的第三条打印语句还没有值。
您的前两个打印语句实际上会在您的第三个打印语句之后执行,即使它看起来不是这样。如果在每个打印语句上创建断点,您将能够看到执行顺序。
因此,为确保数据从Firebase返回,您只应在此处调用数据:
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Manipulate data here
}
如果您希望通话是同步的,则可以执行以下操作:
func retrieveData(user: User) {
//let userID = Auth.auth().currentUser?.uid
let email = user.emailAddress!
// print(email)
databaseRef?.child("userTable").child(email).observe(.value, with: { (snapshot) in
// Get user value
print("whats up ")
if let value = snapshot.value as? [String:String] {
let res = value["posts"]
user.deserialize(data: res!)
if( user === self.u1) {
print("they are same obj") // this will print, so they are pointing to the same address
}
print(self.u1.posts) // this also printed the things I want
}
// ...
})
if( user === self.u1) {
print("they are same obj outside") // this also prints
}
DispatchQueue.main.async{
print(self.u1.posts) // Now called sequentially
}
}