2017-07-17 75 views
0

我正在處理一個大型Firebase數據庫,每個節點至少有6層層次結構以及許多子節點。我想解析整個快照並將其轉換爲對象模型。我發現this解決方案,但在我看來,它是非常低效的解析每個節點的孩子requries調用firebase,這會以指數方式增加延遲。有沒有什麼方法可以在本地完成「ref.observeSingleEvent」,而不是打電話給Firebase?任何其他更好的替代品將不勝感激。Swift Firebase快照到對象模型

+0

是的,你可以下載一個地圖在火力地堡與下它的許多childerns,你不必做超過1個呼叫火力地堡如果所有childern都落在1張地圖下,並且您下載了該地圖。 –

回答

1
//this goes into your call (observeSingleEvent) 
let enumerator = snapshot.children //assuming you use snapshot as name 
    while let rest = enumerator.nextObject() as? FIRDataSnapshot { 
     // this loops through every child in that map 
     let values = (rest as! DataSnapshot).value as? NSDictionary 
     let coins= values?["coins"] as? Int ?? 0 
     //above code looks for a key with username and grabs the value from that. If it is not a string value it returns the default value. 
     //use above code for picture 1 
     if (rest as! DataSnapshot).key == "slot"{ 
     let enumeratorMap1 = (rest as! DataSnapshot).children 
     while let rest2 = enumeratorMap1.nextObject() as? FIRDataSnapshot { 
     let valuesMap1 = (rest2 as! DataSnapshot).value as? NSDictionary 
     //loop through values in new map 
     //use this methodes for looping through maps, as stated in picture 2 
     //keep repeating this method for any child under the map 
      } 
     } 
    } 

圖片1: enter image description here

圖2: enter image description here

+0

這導致了很多臃腫的代碼,但工作方式比其他解決方案更好。 – tectonicpie

+0

@tectonicpie是的我知道,但我認爲沒有其他辦法(如果有的話,我想知道),但它主要取決於你如何構造你的數據。 –

+0

如何使此解決方案與對象數組一起工作?例如 「name」:[{object1},{object2},{object3}] 我可以將名稱及其數組轉換爲NSDictionary,但一旦進入數組內部,就沒有鍵值對,只是對象的值。 – tectonicpie