如何解决核心数据中的对象重复
我有问题,每次保存对象时,它们都会以重复的方式反映在uitableview中,有人知道如何解决它,或者我的代码中有问题吗?
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 attach a photo of my results
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
}
}
解决方法
问题在于numberOfSections(in tableView:)
总是返回4。但是,您似乎并没有以任何方式对数据行进行分组。因此,表视图显示4个不带标题的节,并且由于您没有检查tableView(_ tableView:,cellForRowAt indexPath:)
中的节号,因此每个节中都有四个相同的单元格。
在numberOfSections(in tableView:)
中将4更改为1,重复项将消失。
P.S。附带说明一下,您可能想使用NSFetchedResultsController
而不是仅将项目提取到数组中,它与UITableViewDataSource
的结合非常好。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。