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?
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.
I attach a photo of my results
I attach my code of tableview functions
extension ViewController : UITableViewDelegate,UITableViewDataSource{
func numberOfSections(in tableView: UITableView) -> Int {
return 4
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
items?.count ?? 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let celda = tableView.dequeueReusableCell(withIdentifier: "Celda", for: indexPath);
var detalle = "Lugar de Origen: " + self.items![indexPath.row].origen! + "\n" + "Edad: " + String(self.items![indexPath.row].edad) + "\n" + "Dia: " + String(self.items![indexPath.row].dia.debugDescription)
celda.textLabel?.text = self.items![indexPath.row].nombre
celda.detailTextLabel?.text = detalle
return celda
}
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .normal, title: "Delete") { (action, view, completionHandler) in
let personToRemove = self.items![indexPath.row]
self.context.delete(personToRemove)
do{
try self.context.save()
}catch let error {
print("error \(error.localizedDescription)")
}
self.fetchPeople()
self.tableView.reloadData()
}
delete.backgroundColor = UIColor.red
let config = UISwipeActionsConfiguration(actions: [delete])
config.performsFirstActionWithFullSwipe = false
return config
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 80
}
}
The problem is that numberOfSections(in tableView:)
always returns 4. However, you don't seem to group your data rows in any way. Therefore, the table view displays 4 sections without headers and because you aren't checking the section number in tableView(_ tableView:, cellForRowAt indexPath:)
, you get four identical cells in each section.
Change 4 to 1 in numberOfSections(in tableView:)
and the duplicates will go away.
P.S. On a side note, you might want to use NSFetchedResultsController
instead of just fetching items into an array, it couples really well with UITableViewDataSource
.