2017-04-25 27 views
0

我想檢查我的數據庫中的帖子數,並將其作爲我的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 
     } 
+1

你需要在加載表之前加載數據視圖。 – rmaddy

回答

0

numberOfRowsInSection是查詢數據庫的錯誤地方。

無論如何,該方法將在閉包完成執行前返回requestPostcount和默認值。

您需要找到一個更好的地方來查詢您的數據庫,以便在調用numberOfSections時,數據已經可用。

0

您誤解了異步方法的工作原理。您不能在numberOfRows方法中對遠程數據庫執行異步查詢並返回一個值。

調用異步方法的函數不可能返回異步方法的結果作爲函數結果。

您需要設置模型以使其中沒有數據,發送數據庫查詢,解析結果,然後在完成閉包中更新模型,然後在主線程上告訴表視圖更新。

+1

不可能有一個調用async方法的函數將async方法的結果作爲函數結果返回。 - >當然可以,如果你等結果。在'tableView(numberOfRowsInSection:)'方法調用中絕對不可取,儘管 – Alexander

+0

@Alexander:嗯,號碼將異步函數變成同步函數。因此我的發言是站立的 –

+0

也許是一個術語問題,但異步函數仍然是異步的。執行異步函數調用,並繼續執行下一條指令。恰好碰巧這些指令之一是阻塞等待 – Alexander

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 
     }