簡體   English   中英

在Firebase / Swift中退出OvserveEventType關閉后,將清除數組

[英]Array is cleared after exiting OvserveEventType closure in Firebase/Swift

我有一個具有以下結構的數據庫:

{
  "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放置在數組中,以便稍后在表中使用。 但是,它似乎清除了我的整個數組,一旦它退出了watchEventType外殼。 我在整個循環中放置了一些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
        }

    })

誰能告訴我發生了什么/如何解決?

解決了! 下面是用@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()********

    })

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM