やりたいこと
アプリを立ち上げると,Firebase Realtime Database
からデータを取得し,そのデータの要素の数と同じCellを表示させたい.
コード
Databaseから読み込んだデータの要素の数をプリントしている
Swift
1 2import UIKit 3import Firebase 4import FirebaseUI 5 6class FirstViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 7 8 //Databaseを参照したデータを格納するプロパティ 9 var ref: DatabaseReference! 10 //Databaseから読み込んだデータを格納するプロパティ 11 var names: [String: Int] = [:] 12 13 14 override func viewDidLoad() { 15 super.viewDidLoad() 16 //Databaseを参照 17 self.ref = Database.database().reference() 18 //Databaseから読み込んだデータを格納 19 self.ref.observeSingleEvent(of: .value) { (DataSnapshot) in 20 self.names = DataSnapshot.value as! [String: Int] 21 print(self.names.count) // 3 22 } 23 print(self.names.count) // 0 24 } 25 26 27 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 28 print(self.names.count) // 0 29 //Databaseから読み込んだデータの要素の数だけのCellを返す 30 return self.names.count 31 } 32 33 34 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 35 let cell = tableView.dequeueReusableCell(withIdentifier: "nameCell", for: indexPath) 36 return cell 37 } 38}
考えられること
self.ref.observeSingleEvent(of: .value) { (DataSnapshot) in self.names = DataSnapshot.value as! [String: Int] }
よりも
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.names.count }
の方が先に処理されてしまっている.
知恵をお貸しください
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/31 04:31
2019/08/31 04:33