如何达到childByAutoId()背后的值

问题描述 投票:1回答:1

当我保存用户创建的项目时,我使用以下代码:

let ref = Database.database().reference(fromURL: "https://projectsupport-e475b.firebaseio.com/").child("Projects").childByAutoId() 
let values = ["ProjectTitle": ProjectTitle, "Fighters": EarlySupporters, "Tags": Tags, "TotalFighters": "0", "Description": Description, "ProfileImage": profileImageUrl, "Creator": self.username!] as [String : Any]


ref.updateChildValues(values)

这是我的数据库:

Projects:
        |
        -------KyHzk8VtHitcLlYw1MT
              | 
              - ProjectName: "ProjectNameTest"
              |
              - Creator: "CreatorTest"
              - And so on...

当我尝试检索数据时,我使用以下代码:

Database.database().reference().child("Projects").observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String : AnyObject]
            {
                let project = Project(dictionary: dictionary)
                //The following line was the problem:

                //project.setValuesForKeys(dictionary)


                //I'm still not sure why that solved the problem.

                print(project)
                DispatchQueue.main.async {
                    self.tableView.reloadData()
                }
            }

            print(snapshot)
        }, withCancel: nil)

这导致崩溃如下:

由于未捕获的异常'NSUnknownKeyException'而终止应用程序,原因:'[setValue:forUndefinedKey:]:此类不是密钥值编码兼容的密钥创建者。

我如何访问数据?我如何获得钥匙?

ExamleOfProject

swift firebase firebase-realtime-database key
1个回答
0
投票

我知道了 !我认为这些代码行存在一些问题:

let project = Project(dictionary: dictionary) project.setValuesForKeys(dictionary)

变量项目的类型是什么?在前面有let关键字,你说你的project变量是一个不可变类型。设置后,您无法修改它。并且,这正是您在下一行使用setValueForKeys功能所要做的。尝试用project制作var project = Project(dictionary: dictionary)作为可变类型,看看是否有任何区别。

© www.soinside.com 2019 - 2024. All rights reserved.