前提・実現したいこと
Realtime Database に保存しているデータを、TableView に表示しています。
画面を更新する度に、TableView に表示されるデータが倍に増えて困っています・・・
viewDidLoad()を実行する度に一度 TableView の中身をリセット(空)したいのですが方法がわかりません。
お詳しい方がいらっしゃいましたら、ご教示をお願いします。
該当のソースコード
swift
1import UIKit 2 3import Firebase 4import SwiftyJSON 5import FirebaseAuth 6import FirebaseDatabase 7 8class History { 9 10 var time:String? 11 var status:String? 12 var price:Int? 13 14 init(time: String?, status: String?, price: Int?) { 15 self.time = time 16 self.status = status 17 self.price = price 18 } 19 20} 21 22class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { 23 24 var ref:DatabaseReference! 25 26 // 履歴をテーブルビューに表示 27 var historys = [History]() 28 29 //リストに表示する件数はある分すべてに設定されています 30 func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 31 return historys.count 32 } 33 34 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 35 let cell = tableView.dequeueReusableCell(withIdentifier: "historyCell", for: indexPath) as! HomeViewControllerTableViewCell 36 let history = historys[indexPath.row] 37 cell.timeLabel.text = history.time 38 cell.statusLabel.text = history.status 39 cell.priceLabel.text = "(history.price ?? 0)" 40 return cell 41 } 42 43 44 override func viewDidLoad() { 45 super.viewDidLoad() 46 47 tableView.dataSource = self 48 tableView.delegate = self 49 50 51 LoadHistory() 52 53 } 54 55 56 57 //データベースから履歴に表示させるデータを取り出す 58 func LoadHistory() { 59 60 ref = Database.database().reference().child("Action") 61 ref.queryOrdered(byChild: "number").queryEqual(toValue: argString).observeSingleEvent(of: .value, with: {(snapshot) in 62 for item2 in snapshot.children { 63 let snap2 = item2 as! DataSnapshot 64 let dict2 = snap2.value as! [String: Any] 65 let time = dict2["time"] as? String 66 let status = dict2["status"] as? String 67 let price = dict2["price"] as? Int // "price"は Int型 68 //取得したTimeのデータをプリント 69 print(dict2 as Any) //確認用でdict2を出力(成功) 70 let hist = History(time: time, status: status, price: price) 71 self.historys.append(hist) 72 } 73 self.historys = self.historys.reversed() 74 self.tableView.reloadData() 75 }) 76 } 77 78 override func didReceiveMemoryWarning() { 79 super.didReceiveMemoryWarning() 80 } 81 82 83 84 85} 86 87//今回の事案と関係のないコードは省略しています 88 89
試したこと
毎回データベースから値を取得して追加してるから、viewDidLoad()のはじめに
self.historys = self
と追加してhistorysに入ってるデータを初期化?できるかなと思ったんですが上手くいきませんでした。
補足情報(FW/ツールのバージョンなど)
Swift5
Xcode
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/25 06:53
2021/09/09 08:00