我一直在爲這一整天奮鬥,它似乎沒有任何意義,因爲我有非常相似的代碼工作正常。我試過了所有的東西,我試着做一個單獨的方法來返回一個字符串數組,但沒有一個工作。每次,當在括號之後訪問括號(在讀取「print(self.postIDs)」的行後面)時,postIDs數組被設置爲null。感謝您給我提供的任何幫助。因swift中的for循環而無法修改數組?
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 []
的原因是塊'observeSingleEvent'中的代碼與你的其他函數不在同一個線程中。其餘的在主線程中,而'observeSingleEvent'在後臺運行。它們是異步的。您的數據完成加載後,您需要獲取'postIDs'。 – Lawliet
您得到期望值的聲明在閉包中。這會導致關閉塊的延遲執行。你可以嘗試檢查一個完成處理程序是否可以被執行,否則你應該在關閉本身內使用數組完成所需的東西。 – Rishabh
在block'observeSingleEvent'內部和外部放置斷點,您將看到區別。 – Lawliet