首页 > 解决方案 > 将项目动态添加到 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()

            })

标签: swiftfirebaseuitableviewfirebase-realtime-databasereloaddata

解决方案


您需要使用observeSingleEvent而不是observe

childRef.observeSingleEvent(of: .value) { snapshot  in 
   ////         
}

或者

childRef.observe(.childAdded) { snapshot  in 
   ////         
}

或者

childRef.observe(.value, with: { snapshot in
   self.myRecipes.removeAll ()
   /// 
}

observe每次更改都再次获取所有数据,这与observeSingleEvent获取所有数据一次不同


推荐阅读