【问题标题】:Duplicate cells on each load of tableView from coredata每次从 coredata 加载 tableView 时重复单元格
【发布时间】:2021-12-09 13:49:30
【问题描述】:

该视图显示 CoreData 中每条记录的重复行,这些记录在每次重新加载时不断增加。代码如下。 每当我添加记录时会发生什么,然后我查看记录它会显示记录。然后我点击返回主页,然后当我点击查看记录时,我看到了相同记录的副本。所以现在我有 2 条相同的记录。谁能帮助我,我认为问题出在表格视图中,所以这是我的表格视图控制器代码

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)
        }
    }
}

【问题讨论】:

  • 前十行左右说明了一切。

标签: ios swift xcode core-data duplicates


【解决方案1】:

您的代码繁琐得令人难以置信。

  • 首先,永远不要在任何类之外声明数据源。
  • 其次,永远不要使用函数来构建数组作为表视图数据源。
  • 第三个firstRun 毫无意义,因为无论如何viewDidLoad 只被调用一次。
  • 第四,而不是过滤接收到的记录手动将谓词应用于获取请求

此外,强烈建议始终以单数形式 (Record) 命名 Core Data 实体,并使用该实体的特定通用获取请求。

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
    }

 ...

【讨论】:

    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-10
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    相关资源
    最近更新 更多