我的数据库结构如下:
"routines": {
"users unique identifier": {
"routine unique identifier": {
"routine_name": "routine name",
"routine_create_date": "routine created date",
"exercises": {
"exercise name": {
"Sets": "number of sets"
}
}
}
}
}
检索数据时,我想将每个
routine
存储为一个对象,以加载到UITableView
中。我使用的例程结构是:struct Routine {
var routineName: String!
var routineExercisesAndSets: [String:Int]!
}
如何从中检索值,以便对于每个
Routine
模型,我都可以拥有Routine(routineName: "Legs", routineExercisesAndSets: ["Squats":4,"Lunges":4,"Calf Raises":4])
,其中练习词典为exercise name
:number of sets
。我目前使用的是其他结构,几乎可以通过以下方法获得所需的结果:
let ref = FIRDatabase.database().reference().child("routines").child(userId)
var routineTemp = Routine()
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
routineTemp.routineName = dictionary["routineName"] as! String
let enumerator = snapshot.childSnapshot(forPath: "exercises").children
var exercisesAndSets = [String:Int]()
while let item = enumerator.nextObject() as? FIRDataSnapshot {
exercisesAndSets[item.key] = item.value! as? Int
}
routineTemp.routineExercisesAndSets = exercisesAndSets
print(routineTemp)
}
} , withCancel: nil)
最佳答案
我设法使用以下代码获取每个练习的值及其各自的numberOfSets
:
guard let userId = FIRAuth.auth()?.currentUser?.uid else {
return
}
let ref = FIRDatabase.database().reference().child("routines").child(userId)
var routineTemp = Routine()
var exercisesAndSets = [String:Int]()
ref.observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String : AnyObject] {
routineTemp.routineName = dictionary["routineName"] as! String
let enumerator = snapshot.childSnapshot(forPath: "exercises").children
while let item = enumerator.nextObject() as? FIRDataSnapshot {
exercisesAndSets[item.key] = item.childSnapshot(forPath: "numberOfSets").value! as? Int
}
}
routineTemp.routineExercisesAndSets = exercisesAndSets
self.routines.append(routineTemp)
DispatchQueue.main.async {
self.tableView.reloadData()
}
} , withCancel: nil)
如果还有其他人遇到类似的问题,我希望这有助于提供一种获取值的方法的想法。