NSUnknownKeyExeption using firebase and NSobject

我只是一个虾纸丫 提交于 2019-12-12 01:16:39

问题


2018-12-30 15:01:23.228731+0200 iChat[51679:726127] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key username.' (lldb)

Using firebase dictionary to setvalue for a key to NSobject class

import UIKit

class User: NSObject {
var email: String?
var username: String?
}

Function

func fetchUsers() {
    Database.database().reference().child("users").observe(.childAdded) { (snap) in
        if let dictionary = snap.value as? [String : AnyObject]{
        let user = User()
            user.setValuesForKeys(dictionary)
            print(user.username)
        }
    }
}

回答1:


Objective-C inference has been changed in Swift 4. You have to add the @objc attribute to each property

class User: NSObject {
   @objc var email: String?
   @objc var username: String?
}

However setValuesForKeys is very objective-c-ish. There are better (and more light-weight) ways in Swift without the heavy ObjC runtime.

And why are both properties optional? Are users allowed without name and email?

Consider that with non-optionals the compiler will throw an error at compile time if you are going to pass nil.



来源:https://stackoverflow.com/questions/53977874/nsunknownkeyexeption-using-firebase-and-nsobject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!