sweepez sweepez - 1 year ago 106
iOS Question

Firebase sorting clarification on snapshot.value

Was hoping someone could help me understand Firebase snapshot and sorting. Why if you queryOrderedByChild on a FirebaseDBRef, the snapshot.value returns as displayed on the Firebase Database (using the browser), but if you do

for snap in snapshot.children{}
the values do show sorted. Just wanting clarification on why this happens.

Let me explain with example.

let dinoRef = rootRef.child("dino")
let query = dinoRef.queryOrderedByChild("dimensions/height")
query.observeSingleEventOfType(.Value, withBlock: { snapshot in
// This prints to the console unsorted

// This prints to console sorted
for snap in snapshot.children {

Thank you.

Answer Source

A FIRDataSnapshot contains information about the keys of the returns data, the values associated with those keys and the order of the keys. When you call snapshot.children the snapshot the enumerator will return the children in the order you requested.

When you call snapshot.value on a snapshot, it must convert all the information to an NSDictionary. A dictionary has no inherent information on the order of data, so the order of the results is lost at this point.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download