问题
So I have this piece of code that is suppose to fetch users from the database and store them in an Array (drivingUsers). I get no errors but when I run the app it crashes.
func fetchUser() {
FIRDatabase.database().reference().child("user_profiles").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.setValuesForKeys(dictionary) //Error
self.drivingUsers.append(user)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}, withCancel: nil)
}
Error Log:
2017-04-29 00:41:46.842568 VEXI[1745:369755] -[__NSCFNumber length]: unrecognized selector sent to instance 0x174a34500
2017-04-29 00:41:46.844084 VEXI[1745:369755] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0x174a34500'
Any ideas?
回答1:
The error unrecognized selector sent to instance means you tried to set a key to a value of the wrong type. It's not clear from your code what kind of object User is, or what keys are in the dictionary object, but one of the values is not the type that User is expecting for that key.
To fix it, you'll need to cast each value in the dictionary to the right type.
回答2:
... I fixed it.
Replacing
user.setValuesForKeys(dictionary)
with
user.name = dictionary["name"] as? String
user.email = dictionary["email"] as? String
user.picture = dictionary["picture"] as? String
user.facebookID = dictionary["facebookID"] as? String
user.status = dictionary["status"] as? String
user.date_joined = dictionary["date_joined"] as? String
user.last_login = dictionary["last_login"] as? String
user.Longitude = dictionary["Longitude"] as? String
user.Latitude = dictionary["Latitude"] as? String
来源:https://stackoverflow.com/questions/43689839/swift-3-1-setvaluesforkeys-and-firebase-failing-to-retrive-users