0

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)
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
SemarY
  • 49
  • 1
  • 9

1 Answers1

0

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.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • There are better (and more light-weight) ways in Swift without the heavy ObjC runtime. can you give an example in my case – SemarY Dec 30 '18 at 13:45
  • The `Codable` protocol or for only a few properties an initializer which maps each value *manually*. – vadian Dec 30 '18 at 13:49