【发布时间】:2017-08-16 14:12:33
【问题描述】:
我希望你能帮助我: 我尝试将用户数据从 firebase 数据库提取到用户类中并调用“setValuesForKeys”。我确实知道我的类属性必须与 firebase 字典中的完全一样,但我收到错误“此类不符合关键城市的键值编码。”
func fetchUsers(){
Database.database().reference().child("users").observe(.childAdded, with: { (snapshot) in
if let usersDictionary = snapshot.value as? [String: String] {
let users = Userdata()
users.setValuesForKeys(usersDictionary)
}
}, withCancel: nil)
}
我的用户类是
class Userdata: NSObject {
var email: String?
var password: String?
var firstname: String?
var lastname: String?
var street: String?
var streetno: String?
var zipcode: String?
var city: String?
var phone: String? }
firebase 的快照看起来像
Snap (ndLBXXX75Oe9Y1PXrqfISL8A4v82) {
city = Washington;
email = "1@a.com";
firstname = Andre;
lastname = Doe;
password = xxxxxx;
phone = "";
street = "Mainstreet";
streetno = 1;
zipcode = 11111;
}
数据库中的字典看起来像
["city": Washington, "firstname": Andre, "lastname": Doe, "email": 1@a.com, "password": xxxxxx, "streetno": 1, "phone": , "street": Mainstreet, "zipcode": 11111]
到目前为止,我有一个解决方案:
users.city = dictionary["city"]
我的问题/问题:我确实想了解错误消息“此类不符合关键城市的键值编码”背后的问题。因为类和 firebase 快照中的密钥看起来相同。
【问题讨论】:
-
这个错误是因为你正在尝试使用 KVC。在developer.apple.com/library/content/documentation/Cocoa/… 阅读有关 KVC 使用情况的信息。字典没有键城市、电子邮件的属性...这就是您看到错误的原因。您可以遍历字典中的所有键并使用 user.setValue(dictionary[key], forKey: key)
-
查看我的答案,它可以轻松地将快照转换为自定义类 - stackoverflow.com/a/38154998/2019221
-
@StasVolskiy 感谢您的回答和您的循环解决方案。它确实有效。我的解决方案是:
user.firstname = usersDictionary["firstname"]我已经阅读了这个developer.apple.com/documentation/objectivec/nsobject/…,我认为我可以使用字典键并将它们与我的类属性匹配。
标签: swift dictionary firebase firebase-realtime-database