首页 > 解决方案 > 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)
    }
}

标签: swiftuitableviewfirebase

解决方案


该过程是异步的,您需要

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
}

推荐阅读