Ios 核心数据中的重复对象
我有一个问题,每次保存对象时,它们都会以重复的方式反映在uitableview中,有人知道如何解决它吗?或者,如果我的代码中有问题,是否有人知道Ios 核心数据中的重复对象,ios,core-data,xcode4,swift4.2,Ios,Core Data,Xcode4,Swift4.2,我有一个问题,每次保存对象时,它们都会以重复的方式反映在uitableview中,有人知道如何解决它吗?或者,如果我的代码中有问题,是否有人知道 import UIKit import CoreData import Foundation class ViewController: UIViewController { //MARK:= Outles @IBOutlet var tableView: UITableView! //MARK:= variables v
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
我附上我的tableview函数代码
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(在tableView:)
总是返回4。但是,您似乎没有以任何方式对数据行进行分组。因此,表视图显示4个没有标题的节,并且由于您没有在表视图(\uTableView:,cellForRowAt indexPath:)
中检查节号,因此每个节中有四个相同的单元格
将numberOfSections(在tableView:)
中的4更改为1,重复项将消失
另一方面,您可能希望使用,而不仅仅是将项目提取到数组中,它与
UITableViewDataSource
非常好地结合在一起。您可以在实现UITableViewDataSource
的地方共享代码吗?@VadimBelyaev好的,我将其附在上面
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
}