因此,我加载了我的firebase节点,然后将数据附加到数组中以在表视图中使用,但是由于某些原因,除非我在此闭包内,否则我无法访问planitTitles内部的数据。请任何解决方法?我觉得我以前已经做到了。谢谢
func loadFirebase(){
let ref = Database.database().reference()
let planits = ref.child("planits")
planits.observe( .value, with: { (planitsSnapshot) in
for child in planitsSnapshot.children {
let planSnap = child as! DataSnapshot
let planDict = planSnap.value as! [String: Any]
if self.keyForThisPlanit.contains(planSnap.key){
let title = planDict["Planit Title"] as! String
self.planitTitles.append(title)
}
}
})
print(self.planitTitles)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "friendUpdatesCell") as? ViewUpdatesTVCell else { return UITableViewCell() }
cell.randomPlanitNumber.text = planitTitles[indexPath.row]
// CRASHES HERE WITH ERROR OUT OF INDEX
return cell
}
答案 0 :(得分:2)
您需要在for循环后重新加载表
var planitTitles = [String]()
//
func loadFirebase(){
let ref = Database.database().reference()
let planits = ref.child("planits")
planits.observe( .value, with: { (planitsSnapshot) in
self.planitTitles.removeAll() // you may want to clear here to avoid duplications
for child in planitsSnapshot.children {
let planSnap = child as! DataSnapshot
let planDict = planSnap.value as! [String: Any]
if self.keyForThisPlanit.contains(planSnap.key){
let title = planDict["Planit Title"] as! String
self.planitTitles.append(title)
}
}
print(self.planitTitles)
self.tableView.reloadData()
})
}
func numberOfRows(inSection section: Int) -> Int {
return planitTitles.count // to prevent cellForRowAt indexOutOfBounds crash
}