gpt4 book ai didi

ios - TableView 行数函数未正确返回数组项计数?

转载 作者:行者123 更新时间:2023-11-30 13:03:40 24 4
gpt4 key购买 nike

我将一堆数据添加到任何数组中,如下所示:

for (index, location) in locations.enumerate() {

FIRDatabase.database().reference().child("users").child(location.key as! String).observeEventType(.ChildAdded, withBlock: { (snapshot: FIRDataSnapshot) in
if(snapshot.exists()){
print(snapshot)
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
user.id = snapshot.key
user.setValuesForKeysWithDictionary(dictionary)

self.users.append(user)

print(user)

dispatch_async(dispatch_get_main_queue(), {
self.tableView.reloadData()
})

}
}
}, withCancelBlock: nil)
}

所有这些数据都被添加到名为 users 的数组中。然后我像这样返回users.count:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}

出于某种随机原因,每当我的数据附加到用户数组时,行数函数就会停止被调用。

这张图片是一些打印输出的东西。它向您显示数组中项目的数量以及附加所有用户数据后它如何停止:

image

有谁知道为什么会发生这种情况?任何帮助将不胜感激!

最佳答案

在for循环FMDatabase block 中,如果你使用像这样的代码

for (index, location) in locations.enumerate(){
// add element to user array in anotherBlock
}

然后

[tableview reloadData]

那么您可能会在 Users 数组中得到计数 0 或 nil。因为在循环中您尝试使用完成来获取对象,并且如果另一个线程中的数据库 block 则当前线程执行下一个代码而不是等待完成。

这就是为什么你得到 nil,在 users 数组中计数 0。

关于ios - TableView 行数函数未正确返回数组项计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39630373/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com