2016-05-08 115 views
0

離開OvserveEventType閉合之後清零我有此結構的數據庫:陣列處於火力地堡/夫特

{ 
    "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 
     } 

    }) 

誰能告訴我發生了什麼事/如何解決它?

+1

itemNames已經在menuItems返回的值中。您迭代快照,每個id將是一個單獨的子項,您可以從let name = id.value [「itemName」]中獲取名稱。爲什麼在第一個區塊內需要進行另一次觀察? – Jay

+0

嗯,所以我用name = id.value [「itemName」]取代了我的內部觀察。 雖然我退出該塊時仍然清除。 –

+0

下面是我的陣列設置: var itemNames:[String] = [] var itemPrices:[String] = [] var itemDescriptions:[String] = [] –

回答

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()******** 

    })