我有一个如下的JSON结构:
{ "groups" : { "-KAv867tzVgIghmr15CM" : { "author" : "ruben", "name" : "Item A" }, "-KAv87nqLEG1Jtc04Ebn" : { "author" : "ruben", "name" : "Item B" }, "-KAv88yZe8KTfkjAE7In" : { "author" : "ruben", "name" : "Item C" } }, "users" : { "rsenov : { "avatar" : "guest", "email" : "ruben@ruben.com", "groups" : { "-KAv867tzVgIghmr15CM" : "true", "-KAv87nqLEG1Jtc04Ebn" : "true", "-KAv88yZe8KTfkjAE7In" : "true" } } } }
每个用户都有一个带有childByAutoId()键的元素“组”。然后,我有该应用程序中存在的所有组的列表。
每次运行该应用程序时,我都会获取当前用户登录的URL参考,并获取该用户的组列表(在这种情况下,登录的用户是具有3个组的“ rsenov”)。对于该用户所属的每个组,我都会遍历组url参考,以查找该3个组的信息。
我这样做是这样的:
func loadTable() { self.groups = [] var counter = 0 self.meses = [] var tempItems = [String]() DataService.dataService.CURRENT_USER_GROUPS_REF.observeEventType(.Value, withBlock: { snapshot in if let snapshots = snapshot.children.allObjects as? [FDataSnapshot] { tempItems = [] for snap in snapshots { DataService.dataService.GROUPS_REF.childByAppendingPath(snap.key).queryOrderedByChild("name").observeEventType(.Value, withBlock: { snapshot in if let postDictionary = snapshot.value as? Dictionary<String, AnyObject> { tempItems.append(snapshot.value.objectForKey("name") as! String) let key = snapshot.key let group = Group(key: key, dictionary: postDictionary) self.groups.insert(group, atIndex: 0) } counter++ if (counter == snapshots.count) { self.meses = tempItems self.miTabla.reloadData() } }) } } }) }
我认为以这种方式进行迭代不是一个好主意。例如,如果GROUPS_REF网址中的某些子项发生更改,则该代码仅在该嵌套代码中运行,并且由于它没有从for循环中获取的“ snap.key”值,因此该代码不起作用。
在这种情况下,哪种方法是进行良好查询的最佳方法?
ew,这花了一些时间写。主要是因为我不太喜欢iOS / Swift:
let ref = Firebase(url: "https://stackoverflow.firebaseio.com/35514497") let CURRENT_USER_GROUPS_REF = ref.childByAppendingPath("users/rsenov/groups") let GROUPS_REF = ref.childByAppendingPath("groups") var counter: UInt = 0 var groupNames = [String]() CURRENT_USER_GROUPS_REF.observeEventType(.Value, withBlock: { groupKeys in for groupKey in groupKeys.children { print("Loading group \(groupKey.key)") GROUPS_REF.childByAppendingPath(groupKey.key).observeSingleEventOfType(.Value, withBlock: { snapshot in print(snapshot.value) if (snapshot.childSnapshotForPath("name").exists()) { groupNames.append(snapshot.value.objectForKey("name") as! String) } counter++ if (counter == groupKeys.childrenCount) { print(groupNames) } }) } })
顺便说一句,这就是您创建最小的,完整的可验证示例的方式。该代码没有外部依赖性(例如Group和DataService在您的代码中),仅包含与答案有关的内容。
Group
DataService
重要的位:
observeSingleEventOfType
snapshot.childSnapshotForPath("name").exists()