Le cellule Duplicate su ogni carico di tableView da coredata

0

Domanda

La mostra di righe duplicate per ogni record di CoreData che si moltiplicano su ogni ricarica. Il codice è sotto. Quello che succede è quando mi aggiungi record poi l'ho vista record che mi mostra il record. Ho quindi fare clic su indietro per l'homepage, dopo di che quando clicco su visualizza registro vedo la copia del record stesso. Così ora ho 2 stesso record. Qualcuno può per favore aiutarmi con e penso che il problema è nella visualizzazione della tabella così qui è il mio table view controller codice

import UIKit
import CoreData
var Rec = [Records]()
class TableViewController: UITableViewController {
    var firstLoad = true
    func nondel() -> [Records]
    {
        var nodellist = [Records]()
        for note in Rec
        {
            if(note.del == nil)
            {
                nodellist.append(note)
            }
        }
        return nodellist

    }
    override func viewDidLoad() {
        super.viewDidLoad()
        if(firstLoad)
        {
        firstLoad = false
            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let context:NSManagedObjectContext = appDelegate.persistentContainer.viewContext

            let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Records")
            do{
                let results: NSArray = try context.fetch(request) as NSArray
                for result in results {
                    let note = result as! Records
                    Rec.append(note)
                }
            }
            catch
            {
                print("Fetch Failed")
            }
        }

    
    }

    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! TableViewCell
        
        let thisrec: Records!
        thisrec = nondel()[indexPath.row]
        cell.idLB.text = thisrec.id
        cell.nameLB.text = thisrec.name
        cell.lastLB.text = thisrec.last
        cell.genderLB.text = thisrec.gender
        cell.ageLB.text = thisrec.age
        cell.addressLB.text = thisrec.address
        return cell


}
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return nondel().count
    }
    override func viewDidAppear(_ animated: Bool) {
        tableView.reloadData()
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        self.performSegue(withIdentifier: "editNote", sender: self)
        }
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "editNote")
        {
            let indexPath = tableView.indexPathForSelectedRow!
            let recDetail = segue.destination as? AddViewController
            let selectedCell: Records!
            selectedCell = nondel()[indexPath.row]
            recDetail!.selectedCell = selectedCell
            tableView.deselectRow(at: indexPath, animated: true)
        }
    }
}
core-data duplicates ios swift
2021-10-23 03:50:16
1
0

Il codice è incredibile ingombrante.

  • Prima di tutto, mai affermare di essere una fonte di dati al di fuori di qualsiasi classe.
  • In secondo luogo, non usare mai una funzione per costruire una matrice come la tabella di visualizzazione dei dati di origine.
  • Terzo di tutti firstRun è inutile, perché viewDidLoad viene chiamato solo una volta comunque.
  • Quarto di tutti, piuttosto che il filtro record ricevuti manualmente applicare un predicato per la richiesta di recupero

Inoltre, è altamente consigliato di nome Core entità di Dati sempre in forma singolare (Record) e di utilizzare la generica specifica richiesta di recupero di questa entità.

class TableViewController: UITableViewController {
    var records = [Record]()
   
    override func viewDidLoad() {
        super.viewDidLoad()
       
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        let context = appDelegate.persistentContainer.viewContext

        let request : NSFetchRequest<Record> = Record.fetchRequest()
        request.predicate = NSPredicate(format: "del != nil")
        do {
             records = try context.fetch(request)
        } catch { print("Fetch Failed", error) }
    }        
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "myCell") as! TableViewCell
        
        let thisrec = records[indexPath.row]
        cell.idLB.text = thisrec.id
        cell.nameLB.text = thisrec.name
        cell.lastLB.text = thisrec.last
        cell.genderLB.text = thisrec.gender
        cell.ageLB.text = thisrec.age
        cell.addressLB.text = thisrec.address
        return cell
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return records.count
    }

 ...
2021-10-23 04:44:59

In altre lingue

Questa pagina è in altre lingue

Русский
..................................................................................................................
Polski
..................................................................................................................
Română
..................................................................................................................
한국어
..................................................................................................................
हिन्दी
..................................................................................................................
Français
..................................................................................................................
Türk
..................................................................................................................
Česk
..................................................................................................................
Português
..................................................................................................................
ไทย
..................................................................................................................
中文
..................................................................................................................
Español
..................................................................................................................
Slovenský
..................................................................................................................