我整天都在苦苦挣扎,似乎没有任何意义,因为我的代码非常相似,工作正常。我已经尝试了所有的东西,我已经尝试制作一个单独的方法,返回一个字符串数组,但没有一个工作。每当postIDs数组在括号后面访问括号时(在行读取“print(self.postIDs)”之后)被设置为null。谢谢你能给我的任何帮助。
var postIDs = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
let ref = Database.database().reference()
let uid = Auth.auth().currentUser!.uid
ref.child("users").child(uid).child("saved").observeSingleEvent(of: .value, with: { snapshot in
var ids = [String]()
let saved = snapshot.value as! [String:AnyObject]
for (elem, _) in saved {
ids.append(elem)
}
self.postIDs = ids
print(self.postIDs) // returns the values I would expect
})
ref.removeAllObservers()
guard self.postIDs.count >= 1 else {return} // postIDs count is equal to 0 here, and when I print postIDs the result is []
答案 0 :(得分:0)
这是因为
float
适用于后台,其他代码行在回调来之前执行
答案 1 :(得分:0)
检查以下代码
override func viewDidLoad() {
super.viewDidLoad()
usersTableView.dataSource = self
usersTableView.delegate = self
// getSnapShot()
let databaseRef = Database.database().reference()
databaseRef.child("Users").observe(.value, with: { (snapshot) in
if snapshot.exists() {
self.postData = snapshot.value! as! [String : AnyObject]
self.postData.removeValue(forKey: self.appDelegate.KeyValue)
// self.getUserNames(Snapshot: self.postData)
}
else{
print("No users")
}
print(self.postData) //Does not return nil
self.getSnapShot() //Take snapshot outside paranthesis
})
print(self.postData) //Returns nil
}
func getSnapShot() {
print(self.postData) //Value of Snapshot is printed
}