swift - Swift - 完成处理程序后不更新值
问题描述
我是 Swift 编程的新手,并试图为我的 tableView numberOfSections 返回一个值。我也是完成处理程序的新手。如果我进入调试模式并逐行运行我的代码,count 确实会在 numberOfSections 中“更新”。然而,当它到达 return 语句时,count 保持为 0。
override func numberOfSections(in tableView: UITableView) -> Int {
var count = 0
let firebase = ref.child("Menu").child("Category").child("Cookies")
getCount(ref: firebase) { (myCount) in
print("Complete")
count = myCount
}
return count
}
func getCount(ref:DatabaseReference, completion: @escaping (Int) -> ()){
var count = 0
ref.observeSingleEvent(of: .value) { (snapshot) in
count = Int(snapshot.childrenCount)
completion(count)
}
}
解决方案
该过程是异步的,您需要
var count = 0 // instance var
override func viewDidLoad() {
super.viewDidLoad() // you missed this =D
let firebase = ref.child("Menu").child("Category").child("Cookies")
getCount(ref: firebase) { (myCount) in
print("Complete")
count = myCount
self.tableView.reloadData()
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return count
}
推荐阅读
- java - 在fragment之间调用方法时,一定要经过一个activity吗?
- c - 三个输入字符的比较不正确
- c++ - UE4 C++ Inventory Items 在一段时间后发生变化
- blazor-client-side - 如何使用 ValidationSummary 组件在 Blazor (webassembly/wasm) 中显示服务器端验证错误?
- rust - 如何在不需要 Copy 特征的情况下返回引用?
- java - 针对多种情况通过 dataflowinout 流欺骗用户输入
- c# - 当涉及不同模型时,如何将主视图和部分视图值传递给控制器?
- lucene - Lucene Facets:FacetConfig 中的多值选项
- flutter - Flutter 捕捉 RenderOverflow
- python - 如何在蝗虫中执行网络身份验证?