gpt4 book ai didi

ios - 返回闭包外部的变量

转载 作者:行者123 更新时间:2023-11-30 12:30:38 25 4
gpt4 key购买 nike

我想检查数据库中的帖子数量,并将其作为 tableView 中的 numberOfRows 返回。但是,下面的代码不起作用。每次都返回1。我知道这是因为我在闭包内设置了 var requestPostCount,但我不确定如何修复它。

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

var requestPostcount: Int = 1

if segmentOutlet.selectedSegmentIndex == 0 {

// This is temporary
return 1
}

else {
// Query the database to check how many posts are there
ref.child("Request Posts").observe(.value, with: { (snapshot) in
var requestPostCount = Int(snapshot.childrenCount)

// If database is empty, only 1 row is needed to display error message
if requestPostCount == 0 {
requestPostCount = 1
}
})
}

return requestPostcount
}

最佳答案

numberOfRowsInSection 是查询数据库的错误位置。

无论如何,该方法将在闭包完成执行之前返回 requestPostcount 以及您的默认值。

您需要找到一个更好的位置来查询数据库,以便在调用 numberOfSections 时,数据已经可用。

关于ios - 返回闭包外部的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43600205/

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