返回变量外部闭包

时间:2017-04-25 01:37:53

标签: ios swift uitableview

我想检查数据库中的帖子数量,并将其作为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
        }

3 个答案:

答案 0 :(得分:0)

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

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

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

答案 1 :(得分:0)

您误解了异步方法的工作原理。您无法在numberOfRows方法中对远程数据库执行异步查询并返回值。

不可能有一个调用异步方法的函数将async方法的结果作为函数结果返回。

您需要将模型设置为不包含数据,发送数据库查询,解析结果,然后在完成闭包中更新模型,然后在主线程上告诉表视图更新

答案 2 :(得分:0)

您需要在ViewDidLoad中加载数据。获取数据后重新加载tableview,

var requestPostcount:Int = 1 //声明的变量

override func viewDidLoad() {
    super.viewDidLoad()

    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
        }
        tblView.reloadData()
    })
  }

现在 numberOfRowsInSection ,如下所示

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
         if segmentOutlet.selectedSegmentIndex == 0 {
                return 1
            }
         else {
            return requestPostcount
        }
相关问题