【发布时间】:2020-06-09 22:17:01
【问题描述】:
let ref = Database.database().reference(withPath: "items")
ref.observe(.value) { (snapshot) in
guard let dict = snapshot.value as? NSArray else { return }
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
dict.forEach { (value) in
do {
let itemData = try JSONSerialization.data(withJSONObject: value,options: .prettyPrinted)
let item = try decoder.decode(Item.self, from: itemData)
self.items.append(item)
}
catch let err {
print(err.localizedDescription)
}
}
print(self.items) // This
print(self.items[0]) // works
}
并尝试访问 tableview 中的项目:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
itemType = String(describing: (self.items[indexPath.section].item_type)) // terminating with index out of range error
//...
}
发生错误是因为观察方法异步工作并稍后执行,然后 tableview 填充数据。
如何解决?
【问题讨论】:
-
您如何返回 UITableViewDataSource 的部分数量?
-
@Muhammad Afzal 现在它的常量 int 用于测试目的 func numberOfSections(in tableView: UITableView) -> Int { return 3 }
-
这是您的应用崩溃的主要原因,您需要返回 items.count in number of section of you want to use section,如果您想使用 rows 返回行数。
标签: arrays swift uitableview firebase-realtime-database