我有一个具有这种结构的数据库:
{
"users" : {
"8eee4af2-7a02-4c5c-9c2a-5a50623bd681" : {
"menu" : {
"-KHG5aYVJM4iDQqA0EQS" : {
"itemDescription" : "Description 1",
"itemName" : "Item 1",
"itemPrice" : "Price 1"
},
"-KHG5eJUAUbtXZLEF2Fb" : {
"itemDescription" : "Description 2",
"itemName" : "Item 2",
"itemPrice" : "Price 2"
},
"-KHG5hsYhJTrzbqBUPOO" : {
"itemDescription" : "Description 3",
"itemName" : "Item 3",
"itemPrice" : "Price 3"
},
"-KHG5lDw-uQXrKobPDlC" : {
"itemDescription" : "Description 4",
"itemName" : "Item 4",
"itemPrice" : "Price 4"
},
},
},
},
},
我正在尝试将itemNames放在一个数组中,以便稍后在表中使用。但是,一旦退出observeEventType机箱,它似乎就会清除整个阵列。我已经在整个循环中放置了一些print()语句,并发现如果语句直接位于附加代码之下,但是在}}之外,我可以在它附加时打印数组,它只返回一个空阵列。
let menuItems = ref.childByAppendingPath("users/\(ref.authData.uid)/menu")
menuItems.observeSingleEventOfType(.Value, withBlock: { snapshot in
for id in snapshot.children.allObjects as! [FDataSnapshot] {
let itemName = ref.childByAppendingPath("users/\(ref.authData.uid)/menu/\(id.key)/itemName")
itemName.observeEventType(.Value, withBlock:{ snapshot in
self.itemNames.append(snapshot.value as! String)
print(self.itemNames)
//This print returns an array full of itemNames
})
print(self.itemNames)
//This print returns nil
}
})
有谁能告诉我发生了什么/如何解决?
答案 0 :(得分:0)
解决了!使用@jay的答案更新的代码如下,我所要做的就是告诉表在退出循环之前重新加载数据。
let menuItems = ref.childByAppendingPath("users/\(ref.authData.uid)/menu")
menuItems.observeEventType(.Value, withBlock: { snapshot in
//each time I reload this data after submitting a new menu item, I have to clear itemNames, otherwise it adds duplicate items.
self.itemNames = [String]()
self.itemPrices = [String]()
self.itemDescriptions = [String]()
for id in snapshot.children.allObjects as! [FDataSnapshot] {
let name = id.value["itemName"] as! String
self.itemNames.append(name)
let price = id.value["itemPrice"] as! String
self.itemPrices.append(price)
let description = id.value["itemDescription"] as! String
self.itemDescriptions.append(description)
}
//Solution below. MenuTable is the table all of this is being displayed in
******self.menuTable.reloadData()********
})