swift - 此类与键名的键值编码不兼容
问题描述
当我将值传递给采用键值字典的方法时,我遇到了一个问题:
func fetchUserAndSetupNavBarTitle() {
guard let uid = Auth.auth().currentUser?.uid else {
return
}
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: {
(snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
// self.navigationItem.title = dictionary["name"] as? String
let user = User1()
user.setValuesForKeys(dictionary)
self.setupNavBarWithUser(user: user)
}
}, withCancel: nil)
}
我收到此错误:
terminating with uncaught exception of type NSException
this class is not key value coding-compliant for the key name
错误发生在这一行:user.setValuesForKeys(dictionary)
这个问题不是另一个问题的副本,因为每个问题都是由不同的问题引起的
作为对评论的回应,User1 类包含:
class User1: NSObject {
var name: String?
var email: String?
var profileImageUrl: String?
}
解决方案
如果你正在使用 swift 4,你应该这样做:
struct: User1: Codable {
var name: String?
var email: String?
var profileImageUrl: String?
}
if let dictionary = snapshot.value as? [String: Any] {
do {
let data = JSONSerialization.data(withJSONObject: dictionary, options: [])
let user = JSONDecoder().decode(User1.self, from:data)
self.setupNavBarWithUser(user: user)
} catch error {
print (error)
}
}
推荐阅读
- javabeans - 指定的库 jar EJBRemoteInterface.jar 不存在
- angular-material - matRipple 在特定组件中不起作用
- sql - 如何在查询中动态地使用数据透视来包含空值以创建列和行之间的关系
- jackson - 使用 jsonschema2pojo 处理带有 json 模式的序列化和反序列化
- c# - 单元测试 NodaTime 别名 DateTimeZone
- javascript - 如何使用 codeigniter 中的数据库数据在 Select2 中设置值
- javascript - 使用 document.getElementByID() 切换 Mapbox GL JS 图层不起作用
- flutter - Flutter 中如何在没有上下文的情况下访问 Provider
- r - 使用 if 语句但条件长度大于 1 的连续行之间的差异
- google-bigquery - 具有 ARRAY_CONCAT 和 Struct 的不同键