1

I face a problem when I pass values to method that take a key value dictionary:

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)
}

I get this error:

terminating with uncaught exception of type NSException
this class is not key value coding-compliant for the key name

The error occur at this line: user.setValuesForKeys(dictionary)

This question is not a copy to another questions since each question is caused by a different problem

In response to a comment, the User1 class contains:

class User1: NSObject {
    var name: String?
    var email: String?
    var profileImageUrl: String?
}
XeonOp43
  • 11
  • 4
  • So edit your question to show the definition of your User1 class, as well as the contents of your dictionary. It seems pretty clear though that your User1 class does not have a property "name". – Duncan C Sep 04 '18 at 17:54
  • @DuncanC I made the edits you asked me for, I could paste the whole controller code if necessary – XeonOp43 Sep 04 '18 at 18:07
  • Can you also add sample dictionary contents to your question? – Duncan C Sep 04 '18 at 18:49

2 Answers2

0

If you are working with swift 4, you should do:

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)
    }
}
regina_fallangi
  • 2,080
  • 2
  • 18
  • 38
0

Key Value Coding requires Objective-C property accessors. Starting with Swift 3 you must manually declare which property you want to generate these accessors for:

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

Or you can tell the Swift compiler to generate accessors for all properties and functions in your class:

@objcMembers class User1: NSObject {
    var name: String?
    var email: String?
    var profileImageUrl: String?
}
Code Different
  • 90,614
  • 16
  • 144
  • 163