ios - 我无法从 firebase 数据库获取数据作为子类对象

标签 ios swift database firebase datamodel

我的firebase数据如下:

Matches
items
  platinium
  standard
   -LQTnujHvgKsnW03Qa5s
      code: "111"
      date: "27/11/2018"
      predictions
              -0
                prediction: "Maç Sonucu 1"
                predictionRatio: "2"
      startTime: "01:01"

我用下面的代码阅读了这篇文章

databaseHandle = ref.observe(.childAdded, with: { (snapshot) in
        if let matchDict = snapshot.value as? Dictionary<String, AnyObject> {
            let m_key = snapshot.key
            let m = Match(matchKey: m_key, matchData: matchDict)
            self.matches.append(m)
        }
        self.matchesTableView.reloadData()
    })

我有两个数据模型 1 是匹配 2是预测

我可以从数据库读取代码、日期和开始时间,但匹配对象预测数据没有出现,它说它为零,我如何使用匹配对象获取该数据?

最佳答案

您可以按如下方式设置 Model 类

class ListModel: NSObject {
var UID:String?
    var Code:String?
    var Date:String?
    var PredictionsArr:[PredictionsObj]?
    var StartTime:String?
}

class PredictionsObj : NSObject {
    var Prediction : String?
    var PredictionRatio : String?
}

在您的 ViewController 中,您可以添加以下代码

    var ListArr = [ListModel]()

        let ref = Database.database().reference().child("Matches").child(“items”).child(“standard”)
        ref.observe(.childAdded, with: { (snapshot) in
            print(snapshot)
            guard let dictionary = snapshot.value as? [String : AnyObject] else {
                return
            }

            let Obj = ListModel()
            Obj.UID = snapshot.key
            Obj.Code = dictionary["code"] as? String
            Obj.Date = dictionary["date"] as? String
            Obj.StartTime = dictionary["startTime"] as? String

            let myPredictionsArr  = dictionary["predictions"] as? NSArray
            var myPredictionsObj = [PredictionsObj]()
            if myPredictionsArr != nil{
                for dict in myPredictionsArr as! [[String: AnyObject]]  {
                    let detail = PredictionsObj()
                    detail.Prediction = dict["prediction"] as? String
                    detail.PredictionRatio = dict["predictionRatio"] as? String
                    myPredictionsObj.append(detail)
                }
            }
            Obj.PredictionsArr = myPredictionsObj

            self.ListArr.append(Obj)
            self.ListTV.delegate = self
            self.ListTV.dataSource = self
            self.ListTV.reloadData()
        }, withCancel: nil)

关于ios - 我无法从 firebase 数据库获取数据作为子类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53499780/

相关文章:

mysql - 如何对可以具有 1-M 个多个实体的实体建模?

swift - 既然 Xcode 9 已经发布,我可以从 Xcode 8.3.3 提交和部署应用程序而不更新到 Xcode 9 吗?

mysql - MySql 查询中的多个 Order By

ios - React Native Ios发行版应用程序卡在白屏上,一段时间后崩溃,而在正常构建中完美运行

ios - CloudKit批处理结果为 "Limit Exceeded"

iphone - iOS UIwebView 身份验证 Cookie

ios - 如何使用 UITableViews 深入查看 plist?

ios - 表格 View 单元格偏移

ios - Swift 4 - 将 1 或 0 从 mysql 转换为 bool

swift - 使用 https ://cocoapods. org/pods/SQLite.swift 连接两个 sqlite 数据库时出现问题