我正在从Firebase实时数据库中获取数据到我的tableView中,单击后的单元格将使用来自Firebase的tableView中的数据打开一个新视图,但是我需要tableView来侦听firebase数据中的更改,所以我做了一个侦听器,但是每次关闭并重新打开viewcontroller时,tableView不会reloadData(),它只是将新数据添加到tableView中的数组中,而不会删除旧的数组数据,这使得每次关闭并重新打开视图时,列表都会翻倍控制器
我可以使用什么代码删除旧的tableView数据并将新的数据重新加载到其中,它的长度是相同的,如果没有,则就像更新一样
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self
tableView.delegate = self
dataService()
searchController.searchResultsUpdater = self
searchController.obscuresBackgroundDuringPresentation = false
searchController.searchBar.placeholder = "Search NightClubs"
navigationItem.searchController = searchController
definesPresentationContext = true
searchController.searchBar.scopeButtonTitles = ["All", "Barrie", "Toronto", "London"]
searchController.searchBar.delegate = self
tableView.tableFooterView = searchFooter
}
override func viewWillAppear(_ animated: Bool) {
if let selectionIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRow(at: selectionIndexPath, animated: animated)
}
super.viewWillAppear(animated)
}
func dataService() {
DataService.ds.REF_BARS.observe(.value, with: { (snapshot) in
print(snapshot.value as Any)
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
print(snap)
if let barData = snap.value as? Dictionary<String, AnyObject> {
let bar = NightClubs(barData: barData)
self.nightClubs.append(bar)
print(self.nightClubs)
self.tableView.reloadData()
}
self.tableView.reloadData()
}
self.tableView.reloadData()
self.smallerNightClubs = self.nightClubs//.filter { $0.promoted == "Yes"}
}
self.tableView.reloadData()
})
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if isFiltering() {
searchFooter.setIsFilteringToShow(filteredItemCount: filteredNightClubs.count, of: smallerNightClubs.count)
return filteredNightClubs.count
}
searchFooter.setNotFiltering()
return nightClubs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "searchCell") as! searchCell
let nightClub: NightClubs
if isFiltering() {
nightClub = filteredNightClubs[indexPath.row]
} else {
nightClub = nightClubs[indexPath.row]
}
cell.locationTextLabel.text = nightClub.location
cell.nameTextLabel.text = nightClub.name
return cell
}
答案 0 :(得分:1)
您需要在下一次追加之前清除数组,例如
self.nightClubs.removeAll()
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {