ios - 如何使用 Firebase 数据库填充对象数组

标签 ios swift firebase firebase-realtime-database

我无法创建从 Firebase 数据库返回 Product 对象数组的函数。

我尝试使用闭包中的开关将变量设置为其各自的名称,然后在设置所有变量后实例化该对象。我尝试使用闭包的范围来尝试访问“检索到的值”。下面是我的 Firebase 数据库、产品对象和函数的快照。


 func createArray() -> [Product] { 

        var newArray = [Product]()
        let ref = Database.database().reference()
        var productName = String()
        var productHealth = String()
        var productPrice = 0
        var productImage = String()

        for bigIndex in 0..<7 {
            for smallIndex in 0..<4{
                ref.child("masterSheet/\(bigIndex)/\(smallIndex)").observeSingleEvent(of: .value) { (snapshot) in let retrievedValue = snapshot.value}
                //I used to have a switch statement here that went like
                //switch smallIndex{ case 0: productPrice = retrievedValue as! String }

            }
            let completeProduct = Product(productName: productName, productHealth: productHealth, productPrice: productPrice, productImage: productImage)
            newArray.append(completeProduct)
        }
        return newArray
    }

产品对象:

import Foundation
import UIKit

class Product {
    var productName: String
    var productHealth: String
    var productPrice: Int
    var productImage: String

    init(productName: String, productHealth: String, productPrice: Int, productImage: String ){
        self.productName = productName
        self.productHealth = productHealth
        self.productPrice = productPrice
        self.productImage = productImage

    }
}

我的目标是生成数据库中所有项目的数组。

最佳答案

您需要从smallIndex中获取值并将其设置到modelClass Product中,如下所示:

     func createArray() -> [Product] { 

            var newArray = [Product]()
            let ref = Database.database().reference()

            for bigIndex in 0..<7 {
                for smallIndex in 0..<4{
                    ref.child("masterSheet/\(bigIndex)/\(smallIndex)").observeSingleEvent(of: .value) { (snapshot) in let retrievedValue = snapshot.value}
                    //I used to have a switch statement here that went like
                    //switch smallIndex{ case 0: productPrice = retrievedValue as! String 

          let singleProduct = Product()
          singleProduct.productName = "fetch value from small index"
          singleProduct.productPrice = retrievedValue  
          sigleProduct.productHealth = "fetch value from small index"


                newArray.append(singleProduct)

}

                }

            }
            return newArray
        }

关于ios - 如何使用 Firebase 数据库填充对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57231179/

相关文章:

iOS AUSampler audiounit - EXS 音频文件的文件路径问题?

ios - UITableViewCell UILabel 多行对齐

ios - 每次调用 ViewdidLoad

objective-c - 检测自定义表格单元格内多个 UI View 的点击/触摸的理想方法是什么?

cordova - 当应用程序在前台时,系统托盘中的 FCM 通知

ios - 在单击按钮时插入自定义 UITableViewCell

IOS 7 按钮背景不起作用

ios - 快速将 float 组写入 wav 音频文件

ios - 重置密码时将用户重定向到 iOS 应用程序

javascript - 使用 json 文件将日期/时间戳导入 Firebase Cloud Firestore