首页 > 解决方案 > 此类与键名的键值编码不兼容

问题描述

当我将值传递给采用键值字典的方法时,我遇到了一个问题:

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

解决方案


如果你正在使用 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)
    }
}

推荐阅读