当我从Firebase获取数据时,将其添加到数组中,并获取它的计数,其计数为4,但数据库中只有一个对象。
除此之外,当我尝试通过索引访问数组中的值时,即使是0,我也会得到错误"索引超出范围"。
class GroupsViewController: UIViewController {
var groupNames: [String?] = []
override func viewDidLoad() {
super.viewDidLoad()
ref.child(uid).child("Groups").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let Dict = snapshot.value as? [String : AnyObject]
if Dict != nil {
for (groupIds, accesBool) in Dict! {
self.loadGroups(groupIds)
}
}
})
}
func loadGroups(groupID: String) {
ref.child("Groups").child(groupID).child("GroupName").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let GroupName = snapshot.value as? String
print(GroupName) --> Prints the same string 4 times
self.groupNames.append(GroupName)
print(self.groupNames[0]) --> Prints ERROR Index out of range
print(self.groupNames.count) --> Prints 4
})
}
答案 0 :(得分:0)
在for循环中加载组会导致所有问题。
class GroupsViewController: UIViewController {
var groupNames: [String?] = []
var groupIdsArr: [String] = []
override func viewDidLoad() {
super.viewDidLoad()
ref.child(uid).child("Groups").observeEventType(FIRDataEventType.Value, withBlock: { (snapshot) in
let Dict = snapshot.value as? [String : AnyObject]
if Dict != nil {
var newIds: [String] = []
for (groupIds, accesBool) in Dict! {
newIds.append(groupIds)
}
self.groupIdsArr = newIds
// You can create a loop, that loads each value of the array. I inserted this into a tableview, and used indexPath.row
self.loadGroups(groupIdsArr[0])
}
})
}
func loadGroups(groupID: String) {
ref.child("Groups").child(groupID).child("GroupName").observeSingleEventOfType(.Value, withBlock: { (snapshot) in
let GroupName = snapshot.value as? String
print(GroupName) --> Prints the same string 4 times
self.groupNames.append(GroupName)
print(self.groupNames[0]) --> Prints ERROR Index out of range
print(self.groupNames.count) --> Prints 4
})
}