ios - 从 Firebase 检索数据期间 UITableView 未更新

标签 ios swift firebase firebase-realtime-database

启动时,我将应用设置为从 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/

相关文章:

java - 如何使用 Firebase 结果检索 ListView 中的位置

ios - iOS6 中 UINavigationBar 的顶角被圆化

ios - UILabel 闪烁效果

ios - Swift Mapkit View 中心

xcode - rangeOfString 每次都不返回 nil

java - 如何使用 Android 对 Firestore 进行分页?

angularjs - 如何存储要使用 Firebase 简单登录电子邮件/密码进行身份验证的用户?

ios - 在 iOS Swift 中解析 JSON 格式的最佳方法是什么?

ios - 重新加载 uitableviewcell 时随机滚动,iOs/Swift

ios - Swift:继承 UITextView 或 UICollectionView 并正确初始化