Okay I have a JSON database in Firebase formatted as such (well at least below is a snippet of it)
好吧,我在Firebase中有一个JSON数据库格式化(至少下面是它的片段)
"Trips" : {
"-KnH34F_WZYNHMsTzj0X" : {
"Distance" : 500,
"Transport" : "Walk",
"TripName" : "Work"
},
"-KnH3_WnQaD3piXI7oFf" : {
"Distance" : 900,
"Transport" : "Bike",
"TripName" : "Test"
},
"-KnH7yi4bl2oM6LobPQv" : {
"Distance" : 50,
"Transport" : "Bike",
"TripName" : "Test"
},
I then have the below code to sift through the data and append it into an array of Trip objects.
然后我有下面的代码来筛选数据并将其附加到Trip对象数组中。
Database.database().reference().child("Users").child(user).child("Trips").observe(DataEventType.childAdded, with: { (snapshot) in
let dict = snapshot.value as? NSDictionary
if dict?["Distance"] != nil {
self.commuteBuilder.distance = dict?["Distance"] as? Double
}
if dict?["TripName"] != nil {
self.commuteBuilder.title = dict?["TripName"] as? String
}
if dict?["Transport"] != nil {
self.commuteBuilder.transportType = (dict?["Transport"] as? String)
}
// if self.commuteBuilder.isFilled(){
self.commuteArray.append(self.commuteBuilder)
print("Append")
self.commuteTableView.reloadData()
// }
})
When I set breakpoints the new commuteBuilder object correctly fills the data but once appended, every value in the commuteArray ends up having the same data as the last object added to it.
当我设置断点时,新的commuteBuilder对象正确地填充数据,但是一旦附加,commuteArray中的每个值最终都会与添加到它的最后一个对象具有相同的数据。
So in the above example the array would end up with 3 entries but they would all have TripName: Test and Distance: 50 and Transport "Bike"
所以在上面的例子中,数组最终会有3个条目,但它们都有TripName:Test和Distance:50和Transport“Bike”
I also know the codes messy, I've been struggling with it a bit.
我也知道代码杂乱,我一直在努力。
1 个解决方案
#1
1
self.commuteArray.append(self.commuteBuilder)
this is I think where it goes wrong. Make a temporary commuteBuilder object. Put the retrieved data in that temp object. Append that temp object to your array.
这是我认为哪里出错了。制作一个临时的commuteBuilder对象。将检索到的数据放在该临时对象中。将temp对象追加到数组中。
#1
1
self.commuteArray.append(self.commuteBuilder)
this is I think where it goes wrong. Make a temporary commuteBuilder object. Put the retrieved data in that temp object. Append that temp object to your array.
这是我认为哪里出错了。制作一个临时的commuteBuilder对象。将检索到的数据放在该临时对象中。将temp对象追加到数组中。