此类不符合键值编码的键名

时间:2018-09-04 17:47:44

标签: 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?
}

2 个答案:

答案 0 :(得分:0)

如果您使用的是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)
    }
}

答案 1 :(得分:0)

键值编码需要使用Objective-C属性访问器。从Swift 3开始,您必须手动声明要为其生成这些访问器的属性:

class User1: NSObject {
    @bjc var name: String?
    @objc var email: String?
    @objc var profileImageUrl: String?
}

或者您可以告诉Swift编译器为类中的所有属性和函数生成访问器:

@objcMembers class User1: NSObject {
    var name: String?
    var email: String?
    var profileImageUrl: String?
}