启动时,我将应用设置为从 Firebase 检索数据、创建对象并将它们添加到数组中,然后再将它们添加到 UITableView 中。即使每个对象都是单独创建的,项目也会被创建,但不会添加到 UITableView 中,直到创建数据中的每个对象为止。
Firebase 在主线程上运行,因此这不是 GCD 问题。我正在 viewDidLoad 中运行retrieveData()。
看起来这些项目被放入内存中(没有添加到表格 View 中?)并继续堆叠,直到创建所有项目。此时,所有内容都已加载到 TableView 中,并且内存使用量恢复正常。如果有足够的项目,这会导致极高的内存使用率和崩溃。
func retrieveData(){
let dateString = getDate()
ref = Database.database().reference()
ref.child("orders/").child(Auth.auth().currentUser!.uid).child(dateString).child("products").observeSingleEvent(of: .value, with: { (snapshot) in
let value = snapshot.value as? NSDictionary
if (value != nil){
for (key) in value! {
let item = key.value as? [String:Any]
let (barcode, name, _, bottleSize) = self.getInfo(code: item!["code"]! as! String)
self.generateItem(barcode: barcode, name: name, bottleSize: bottleSize, quantity: item!["quantity"]! as! String, isInitial: true)
}
}
}) { (error) in
print(error.localizedDescription)
}
}
func generateItem(barcode: String, name: String, bottleSize: String, quantity: String, isInitial: Bool = false) {
let i = item(code: barcode, name: name, size: bottleSize, quantity: quantity)
order.append(i)
print("Item Created --- ", order[order.count - 1].name,order[order.count - 1].quantity,order[order.count - 1].code)
let indexPath = IndexPath(row: order.count - 1, section: 0)
orderTableView.beginUpdates()
orderTableView.insertRows(at: [indexPath], with: .automatic)
orderTableView.endUpdates()
// Update Firebase database
if (isInitial == false){
updateDatabase()
}
}
最佳答案
首先尝试构造item
对象并附加到数组,然后直接调用reloadData()
。看看它是如何工作的。
let value = snapshot.value as? NSDictionary
if (value != nil){
for (key) in value! {
let item = key.value as? [String:Any]
let (barcode, name, _, bottleSize) = self.getInfo(code: item!["code"]! as! String)
let i = item(code: barcode, name: name, size: bottleSize, quantity: quantity)
order.append(i)
}
orderTableView.reloadData()
}
关于ios - 从 Firebase 检索数据期间 UITableView 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54564216/