将项目动态添加到TableView中导致重复的单元格

问题描述 投票:1回答:1

我有一个可从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()

            })
swift firebase uitableview reloaddata
1个回答
0
投票

您需要使用observeSingleEvent而不是observe

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

OR

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

OR

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

[observe每次更改都再次获取所有数据,不像observeSingleEvent一次获取所有数据

© www.soinside.com 2019 - 2024. All rights reserved.