swift - 如何达到 childByAutoId() 背后的值(value)

标签 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)

这会导致崩溃,如下所示:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key Creator.'

我如何访问数据?我如何获得 key ?

ExamleOfProject

最佳答案

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

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

你的变量 project 是什么类型? 在它前面加上 let 关键字,你是说你的 project 变量是一个不可变类型。设置后,您将无法修改它。而且,这正是您在下一行使用函数 setValueForKeys 尝试执行的操作。尝试使用 var project = Project(dictionary: dictionary)project 设为可变类型,看看是否有任何区别。

关于swift - 如何达到 childByAutoId() 背后的值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47205093/

相关文章:

javascript - 输入聊天消息时 Firebase 发出警告

ios - Swift:让 subview Controller 保持原位,即使使用新 Controller ?

ios - 从 UITableView 取消注册 UINib

firebase - 如何在 flutter 中模拟 FirebaseApp

ios - 24 小时后 Firebase 授权出现奇怪状态

ios - Swift Firebase "Cannot assign value of type ' Information' to type 'NSDictionary?' "

ios - Swift-在标签栏 Controller 中自定义多个导航栏

Swift 的三元条件运算符从两个非可选值返回可选值?

javascript - 如何使用来自两个独立 Firebase 集合的数据执行嵌套 v-for

javascript - 如何从 Firebase 获取 PWA 数据