swift - 将项目动态添加到 TableView 导致重复单元格
问题描述
我有一个从 Firebase 数据库动态加载数据的表视图。我还有一个添加按钮,允许用户在必须更新表视图之后在 Firebase 数据库中添加并再次从 firebase 和新添加的项目重新加载数据。但是,我遇到了一个问题,即添加项目后表格视图中的数据重复。我试图清除数据源数组,然后重新加载表视图数据,但它不起作用。这是我的代码:
override func viewDidLoad()
{
recipeTableView.delegate = self
recipeTableView.dataSource = self
// clear the array
myRecipes.removeAll()
// get recipes
getRecipes()
}
表视图扩展功能
func numberOfSections(in tableView: UITableView) -> Int
{
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return myRecipes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
recipe = self.myRecipes[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "MyRecipeCell")
as! UIMyRecipesCell
cell.setRecipe(recipe: recipe!)
}
从火力基地获取数据的方法
func getRecipes()
{
self.myRecipes.removeAll()
childRef.observe(.value, with: { snapshot in
for child in snapshot.children
{
//create the object and get the info from the fire base and finally store it MyRecipes array
self.myRecipes.append(recipe)
}
self.recipeTableView.reloadData()
})
解决方案
您需要使用observeSingleEvent
而不是observe
childRef.observeSingleEvent(of: .value) { snapshot in
////
}
或者
childRef.observe(.childAdded) { snapshot in
////
}
或者
childRef.observe(.value, with: { snapshot in
self.myRecipes.removeAll ()
///
}
observe
每次更改都再次获取所有数据,这与observeSingleEvent
获取所有数据一次不同
推荐阅读
- elasticsearch - [...] 上超出了高磁盘水印 [90%],分片将从该节点移出
- javascript - Vue:为什么我的 html 表格列显示为单条直线?
- sql-server - 如何根据同一表中的其他行更新列的值
- html - 我如何能够进行自动化前端测试?
- r - 如何为 Cronbach 的 Alpha & ICC (metafor) 生成森林图?
- javascript - 在Phonegap App中下载HTML/页面为PDF
- python - 如何使用for循环在字典中添加值?
- amazon-web-services - 无法在“您的环境”中查看 AWS Cloud 9 环境
- excel - Excel VBA自动筛选昨天日期,不包括周末
- archlinux - 无法在 Archlinux 上设置 Tapping Enabled Default