Duplicate entries in Core Data

I have a problem, my objects every time I save them are reflected in uitableview in a duplicate way, does anyone know how to solve it or if I have a problem in my code?


Code Block import UIKit
import CoreData
import Foundation
class ViewController: UIViewController {
//MARK:= Outles
@IBOutlet var tableView: UITableView!
//MARK:= variables
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var items: [Entity]?
var duplicateName:String = ""
//MARK:= Overrides
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
fetchPeople()
addPeople(context)
print(" nombres: \(items?.count)")
}
override func viewWillAppear(_ animated: Bool) {
}
//MARK:= Core Data funcs
func fetchPeople(){
do{
self.items = try! context.fetch(Entity.fetchRequest())
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch let error as NSError{
print("Tenemos este error \(error.debugDescription)")
}
}
func addPeople(_ contexto: NSManagedObjectContext) {
let usuario = Entity(context: contexto);
usuario.nombre = "Valeria";
usuario.edad = 25;
usuario.eresHombre = false;
usuario.origen = "Ensenada,B.C"
usuario.dia = Date();
do{
try! contexto.save();
}catch let error as NSError{
print("tenemos este error en el guardado \(error.debugDescription)");
}
fetchPeople()
}
func deletDuplicates(_ contexto: NSManagedObjectContext){
let fetchDuplicates = NSFetchRequest<NSFetchRequestResult>(entityName: "Persona")
//
// do {
// items = try! (contexto.fetch(fetchDuplicates) as! [Entity])
// } catch let error as NSError {
// print("Tenemos este error en los duplicados\(error.code)")
// }
let rediciendArray = items!.reduce(into: [:], { $0[$1,default:0] += 1})
print("reduce \(rediciendArray)")
let sorteandolos = rediciendArray.sorted(by: {$0.value > $1.value })
print("sorted \(sorteandolos)")
let map = sorteandolos.map({$0.key})
print(" map : \(map)")
}
} // End of class



I have tried to solve the error and I have investigated what it is for my array but the truth is that I have not had the solution no matter how much I look for it, if someone could help me it would be of great help.



Could you show the code of your cellForRowAt function for the tableView ?

every time I save them

Where is this save func ? Do you mean line 57 ?

my objects every time I save them are reflected in uitableview in a duplicate way

Do you mean each object is duplicated ? Or just a few ?
Where do you add ONE object ?


You need to find where data is duplicated:
So, add a print("items array", items) everywhere you modify the array

You'll show the record from fetch func. While you fetch the record, remove all the data and then append and reload the tableview. So every time when you call the fetch func it will clear all the previous data and append the new data to your array. So duplication is avoided.

func fetchPeople() {    
do{        
self.items.removeAll().  
self.items = try! context.fetch(Entity.fetchRequest()).          
         DispatchQueue.main.async {              
             self.tableView.reloadData()      
          }
Duplicate entries in Core Data
 
 
Q