2017-04-25 2 views
0

내 데이터베이스의 게시물 수를 확인하고 tableView의 numberOfRows로 반환하고 싶습니다. 그러나 아래 코드는 작동하지 않습니다. 매번 1을 반환합니다. closure 내부에 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

당신의 필요 아래와 같이 변수

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 선언 전망. – rmaddy

답변

0

numberOfRowsInSection은 데이터베이스를 쿼리하는 데 잘못된 위치입니다.

아무튼, 메서드는 closure가 실행을 끝내기 전에 기본값과 함께 requestPostcount를 반환합니다.

numberOfSections가 호출 될 때 데이터를 이미 사용할 수 있도록 데이터베이스를 쿼리 할 수있는 더 나은 위치를 찾아야합니다.

0

비동기 방법의 작동 방식을 잘못 이해합니다. numberOfRows 메서드에서 원격 데이터베이스의 비동기 쿼리를 수행하고 값을 반환 할 수 없습니다.

async 메서드를 호출하는 함수가 함수 결과로 async 메서드의 결과를 반환하도록 할 수 없습니다.

데이터가 없도록 모델을 설정하고 데이터베이스 쿼리를 보내고 결과를 구문 분석 한 다음 모델을 업데이트 한 다음 주 스레드에서 테이블 뷰를 말합니다. 업데이트.

+1

async 메서드를 호출하는 함수를 사용하면 async 메서드의 결과를 함수 결과로 반환 할 수 없습니다. 당신이 결과를 기다리는 것이 확실 할 수 있습니다. 그래도 tableview (numberOfRowsInSection :) 메서드 호출에서는 바람직하지 않습니다. – Alexander

+0

@Alexander : 음, 아니요. 비동기 함수가 동기 함수로 바뀝니다. 따라서 제 진술서가 나타납니다. –

+0

아마도 용어의 문제이지만 비동기 함수는 여전히 비동기입니다. 비동기 함수 호출이 수행되고 실행은 다음 명령어로 계속 진행됩니다. 다음 명령어 중 하나가 차단 대기입니다. – Alexander

0

ViewDidLoad에서 데이터를로드해야합니다. 데이터는 다음의 tableview를 다시 얻기 후에

var에 requestPostcount : 지능 = 1 // 테이블을로드하기 전에 데이터를로드

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     if segmentOutlet.selectedSegmentIndex == 0 { 
       return 1 
      } 
     else { 
      return requestPostcount 
     } 
관련 문제