如何达到childByAutoId()背后的值

时间:2017-11-09 15:01:57

标签: swift firebase firebase-realtime-database key

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

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)

这导致崩溃如下:

  

由于未捕获的异常终止应用程序&#39; NSUnknownKeyException&#39;,原因:&#39; [setValue:forUndefinedKey:]:此类不是密钥值编码兼容的密钥创建者。&#39; < / p>

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

ExamleOfProject

1 个答案:

答案 0 :(得分:0)

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

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

您的变量项目的类型是什么?前面有let个关键字,表示您的project变量是不可变类型。设置后,您无法修改它。而且,这正是您在函数setValueForKeys的下一行尝试做的事情。尝试将project作为var project = Project(dictionary: dictionary)的可变类型,以查看是否存在任何差异。