我認爲這個答案很容易在docs中找到。
我認爲,在類的Android版本中解釋相當不錯:
The Query class (and its subclass, DatabaseReference) are used for reading data. Listeners are attached, and they will be triggered when the corresponding data changes.
我可以在我自己的話解釋,更實用的是這樣的:
您可以使用DatabaseQuery
對象,如DatabaseReference
,但僅限於observe
函數的工作方式,並且沒有任何方法用於操作值,i例如setValue()
等等,也不存在與其他節點相關的任何方法,即父母和子女(child()
等)。
(在你的編碼風格我把代碼的文檔,所以請自由地優化它/把)
這是你如何從DatabaseReference
獲取數據:
var postRef: DatabaseReference!
postRef = Database.database().reference().child("posts")
refHandle = postRef.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
// ...
})
這就是你如何從DatabaseQuery
獲得數據:
// My top posts by number of stars
let myTopPostsQuery = (ref.child("user-
posts").child(getUid())).queryOrdered(byChild: "starCount")
refHandle = myTopPostsQuery.observe(DataEventType.value, with: { (snapshot) in
let postDict = snapshot.value as? [String : AnyObject] ?? [:]
// ...
})
正如你所看到的第二部分保持不變,正如我所提到的,所以檢索數據你處理DatabaseQuery
像DatabaseQuery
。但我不得不同意你的觀點,即文件不是很好,其他語言的解釋更清晰。
該文檔說明了操作系統的問題,它展示瞭如何實例化查詢,但沒有說明一旦實例化後如何從查詢中獲取數據。這是被問及的問題,如何遍歷和訪問查詢中的數據。 – Gruntcakes
@Sausagedioxide對不起,沒有提供足夠好的解釋,我剛剛更新了我的答案,爲您提供了必要的示例,我認爲這將解決您的問題。 – creativecreatorormaybenot
謝謝,SO不會讓我獎賞賞金,我必須等一個小時出於某種原因。 – Gruntcakes