【问题标题】:Duplicate objects in core data核心数据中的重复对象
【发布时间】:2020-12-24 05:58:35
【问题描述】:

我有一个问题,我的对象每次保存时都会以重复的方式反映在 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

附上我的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
}

}

【问题讨论】:

  • 能否分享一下你实现UITableViewDataSource的代码?
  • @VadimBelyaev 好的,我附在上面

标签: ios core-data xcode4 swift4.2


【解决方案1】:

问题是numberOfSections(in tableView:) 总是返回 4。但是,您似乎没有以任何方式对数据行进行分组。因此,表格视图显示 4 个没有标题的部分,并且由于您没有检查 tableView(_ tableView:, cellForRowAt indexPath:) 中的部分编号,因此每个部分中有四个相同的单元格。

numberOfSections(in tableView:) 中的 4 更改为 1,重复项将消失。

附:附带说明一下,您可能想要使用NSFetchedResultsController 而不是仅仅将项目提取到数组中,它与UITableViewDataSource 结合得非常好。

【讨论】:

    猜你喜欢
    • 2012-01-30
    • 1970-01-01
    • 2013-08-17
    • 1970-01-01
    • 2021-08-10
    • 2013-10-21
    • 2012-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多