Swift错误 - 线程1:为setValuesForKeys发出SIGABRT信号

时间:2017-12-30 16:20:48

标签: swift firebase firebase-realtime-database

func fetchUser() {
    Database.database().reference().child("users").observe(.childAdded, with: { (DataSnapshot) in
        if let dictionary = DataSnapshot.value as? [String: AnyObject] {
            let user = User()
            user.setValuesForKeys(dictionary.)
            print(user.name!, user.email!)

        }
    }, withCancel: nil)

}

将我的firebase数据库中的数据添加到我的应用程序时,在将字典中的信息添加到我的用户数组(我为其创建了一个对象)时会抛出SIGABRT错误。我正在做什么的问题是什么?

日志中的错误消息说明了这一点:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<ChatApp.User 0x10bdeec70> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key name.'
*** First throw call stack:
(0x18136a364 0x1805b0528 0x18136a02c 0x181c82630 0x181d1e7dc 0x100016170 0x10001645c 0x10016dd7c 0x100199524 0x1012a92cc 0x1012a928c 0x1012adea0 0x181312544 0x181310120 0x18122fe58 0x1830dcf84 0x18a8af67c 0x100025fbc 0x180d4c56c)
libc++abi.dylib: terminating with uncaught exception of type NSException

1 个答案:

答案 0 :(得分:0)

当您的数据库中的密钥与User对象类中的变量名称不匹配时,会发生这种情况。您可以通过自己手动执行此操作来避免这种情况:

    let reference = Database.database().reference()
    reference.child("users").observe(.childAdded, with: { (snapshot) in

        guard let dictionary = snapshot.value as? [String: AnyObject] else { return }
        guard let username = dictionary["username"] as? String else { return }

        let user = User()
        user.username = username
        // do this for everything the user object needs to hold.

    }, withCancel: nil)