我正在從 firebase 實時資料庫獲取值。我想將這些值存盤到一個陣列中并在 UITableView 中顯示它們。這是正在發生的事情:
我在 viewDidLoad() 函式之前定義了陣列,如下所示:
var taskTitles: [Task] = []
在我的viewDidLoad()函式中,我呼叫另一個函式來生成陣列:
override func viewDidLoad() {
super.viewDidLoad()
//Setting the Title for the nav bar
title = "To Do List"
configureNavigationItems()
taskTitles = createArray() // creating the array of tasks in db
tableView.delegate = self
tableView.dataSource = self
}
在這個函式中,我將資訊傳遞給我的類。任務和任務單元。他們只是在處理任務的標題。
func createArray() -> [Task] {
taskRef = Database.database().reference(withPath: "Tasks")
//getting values from db, storing them in an array.
refHandle = taskRef?.observe(DataEventType.value, with: { snapshot in
for taskSnapshot in snapshot.children {
let nodeA = taskSnapshot as! DataSnapshot
let keyA = nodeA.key
let theTask = Task(title: String(keyA))
self.taskTitles.append(theTask)
print("In the FOR Loop --> ", self.taskTitles)
}
print("outside of FOR Loop --> ", self.taskTitles)
})
print("outside of observe func --> ", taskTitles)
return taskTitles
}
}
但是,它似乎沒有將我的專案保存到陣列中。我做了一些除錯來找出哪里出錯了。希望下面的圖片可以澄清:
知道問題是什么嗎?
uj5u.com熱心網友回復:
您的呼叫taskRef?.observe是異步的。這就是為什么您會在其他行之前看到“outside of observe func --> []”。
發生的事情是您的createArray()函式呼叫observe然后回傳taskTitles仍然是空的。然后您的視圖完成加載并顯示(大概)一個空表。在此之后,該observe函式使用快照呼叫您的閉包并更新taskTitles,但此時tableView已經在螢屏上并且是空的,您必須采取進一步的操作來重新加載它(例如,呼叫reloadData()它)。
也許還值得一提的是,您正在該函式中修改您的屬性,然后回傳它,并將其分配給自身。這也許是多余的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/360596.html
