NSUnknownKeyExeption using firebase and NSobject

2019-08-28 04:51发布

问题:

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.