1

我正在尝试做的事情:

我正在尝试学习如何将 Core Data 与 NSFetchedResultsController 和 UITableViewDiffableDataSource 结合起来,以创建一个简单的表 UI,它可以平滑地处理对 Core Data 中项目表的添加和删除。

我首先构建了一些核心数据代码,然后我添加了一个 TableView,首先将它与手动提取挂钩,然后移动到 NSFetchedResultsController,使用“旧”批量更新行为,现在我正在将该代码移动到使用 DiffableDataSource。

错误:

我有两个用于删除核心数据存储中项目的功能。通过包含删除所有按钮的秘密菜单(通过摇动访问),或通过经典的滑动删除手势。

使用删除所有按钮似乎永远不会出错,但大约 50% 的时间是滑动删除。

错误信息如下:

Fatal error: Unable to delete note: Error Domain=NSCocoaErrorDomain Code=134030 "An error occurred while saving." UserInfo={NSAffectedObjectsErrorKey=(
    "<Note: 0x6000013af930> (entity: Note; id: 0x6000030f9ba0 <x-coredata:///Note/t82D95BE5-DDAE-4684-B19E-4CDA842DF89A2>; data: {\n    creation = nil;\n    text = nil;\n})"
)}: file /Users/philip/Git/Noter/Noter/Noter/Note+CoreDataClass.swift, line 58

编辑:我进一步缩小了错误条件。

该错误仅在我尝试删除最近创建的对象时才会发生。

也就是说,创建一个新的笔记,然后删除相同的笔记。

如果我创建两个笔记,然后删除第一个创建的,我不会出错。删除之后,我同样可以进入并删除第二个注释,没有任何错误。

同样,如果我创建一个便笺,停止模拟器,然后重新启动它,从 Core Data 加载便笺,我可以毫无问题地删除该便笺。

我试过的:

基于错误仅使用滑动删除发生的事实,我认为问题可能与 UITableViewDiffableDataSource 相关,它仍然具有低于标准的文档。

我尝试使用 SQL 查看器(Liya)检查我的核心数据数据库,数据库似乎有我期望的记录,我看到它们被正确创建和删除,同时使用我的调试菜单创建 1 或 1000 条记录,删除使用调试菜单的所有记录也看起来正确。

我启用了-com.apple.CoreData.SQLDebug 1参数,以查看 SQL 输出。同样,插入和删除似乎工作正常。除非发生错误。

我也尝试使用调试器并逐步解决问题,尽管出于某种奇怪的原因,似乎frame variable在我的断点(函数的开头tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool)使用 lldb 命令会导致断点失败,并且代码只是继续到错误。

编码:

这是我认为是相关代码的摘录,完整的源代码也可以在https://github.com/Hanse00/Noter/tree/master/Noter/Noter获得。我将不胜感激任何帮助理解这个问题。

ViewController.swift


import UIKit
import CoreData

// MARK: - UITableViewDiffableDataSource
class NoteDataSource<SectionIdentifierType>: UITableViewDiffableDataSource<SectionIdentifierType, NSManagedObjectID> where SectionIdentifierType: Hashable {
    var container: NSPersistentContainer!

    override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    }

    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            guard let objectID = itemIdentifier(for: indexPath) else {
                fatalError("Unable to find note for indexPath: \(indexPath)")
            }

            guard let note = container.viewContext.object(with: objectID) as? Note else {
                fatalError("Could not load note for id: \(objectID)")
            }

            Note.delete(note: note, from: container)
        }
    }
}

// MARK: - ViewController
class ViewController: UIViewController {
    lazy var formatter: DateFormatter = {
       let formatter = DateFormatter()
        formatter.dateStyle = .short
        formatter.timeStyle = .short
        return formatter
    }()
    lazy var fetchedResultsController: NSFetchedResultsController<Note> = {
        let controller = NSFetchedResultsController(fetchRequest: Note.sortedFetchRequest(), managedObjectContext: self.container.viewContext, sectionNameKeyPath: nil, cacheName: nil)
        controller.delegate = self
        return controller
    }()
    var container: NSPersistentContainer!
    var dataSource: NoteDataSource<Section>!
    @IBOutlet var tableView: UITableView!

    enum Section: CaseIterable {
        case main
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        configureDataSource()
        tableView.delegate = self
    }

    override func viewDidAppear(_ animated: Bool) {
        do {
            try fetchedResultsController.performFetch()
        } catch {
            fatalError("Failed to fetch entities: \(error)")
        }
    }

    func configureDataSource() {
        dataSource = NoteDataSource(tableView: tableView, cellProvider: { (tableView: UITableView, indexPath: IndexPath, objectID: NSManagedObjectID) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: "NoteCell", for: indexPath)

            guard let note = self.container.viewContext.object(with: objectID) as? Note else {
                fatalError("Could not load note for id: \(objectID)")
            }

            cell.textLabel?.text = note.text
            cell.detailTextLabel?.text = self.formatter.string(from: note.creation)

            return cell
        })
        dataSource.container = container
    }

    // MARK: User Interaction

    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {
        if motion == .motionShake {
            addRandomNotePrompt()
        }
    }

    func addRandomNotePrompt() {
        let alert = UIAlertController(title: "Add Random Note", message: nil, preferredStyle: .actionSheet)
        let addAction = UIAlertAction(title: "Add a Note", style: .default) { (action) in
            Note.createRandomNote(in: self.container)
        }
        let add1000Action = UIAlertAction(title: "Add 1000 Notes", style: .default) { (action) in
            Note.createRandomNotes(notes: 1000, in: self.container)
        }
        let deleteAction = UIAlertAction(title: "Delete all Notes", style: .destructive) { (action) in
            Note.deleteAll(in: self.container)
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)

        alert.addAction(addAction)
        alert.addAction(add1000Action)
        alert.addAction(deleteAction)
        alert.addAction(cancelAction)
        present(alert, animated: true)
    }
}

// MARK: - UITableViewDelegate
extension ViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
    }

}

// MARK: - NSFetchedResultsControllerDelegate
extension ViewController: NSFetchedResultsControllerDelegate {

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
        dataSource.apply(snapshot as NSDiffableDataSourceSnapshot<Section, NSManagedObjectID>, animatingDifferences: true)
    }

}

注意+CoreDataClass.swift

import Foundation
import CoreData

@objc(Note)
public class Note: NSManagedObject {

    public class func fetchRequest() -> NSFetchRequest<Note> {
        return NSFetchRequest<Note>(entityName: "Note")
    }

    public class func sortedFetchRequest() -> NSFetchRequest<Note> {
        let request: NSFetchRequest<Note> = fetchRequest()
        let sort = NSSortDescriptor(key: "creation", ascending: false)
        request.sortDescriptors = [sort]
        return request
    }

    public class func createRandomNote(in container: NSPersistentContainer) {        
        let thingsILike = ["Trains", "Food", "to party party!", "Swift"]
        let text = "I like \(thingsILike.randomElement()!)"

        let dayOffset = Int.random(in: -365...365)
        let hourOffset = Int.random(in: -12...12)
        let dateOffsetDays = Calendar.current.date(byAdding: .day, value: dayOffset, to: Date())!
        let date = Calendar.current.date(byAdding: .hour, value: hourOffset, to: dateOffsetDays)!

        let note = Note(context: container.viewContext)
        note.creation = date
        note.text = text

        do {
            try container.viewContext.save()
        } catch {
            fatalError("Unable to save: \(error)")
        }
    }

    public class func createRandomNotes(notes count: Int, in container: NSPersistentContainer) {
        for _ in 1...count {
            createRandomNote(in: container)
        }
    }

    public class func delete(note: Note, from container: NSPersistentContainer) {
        do {
            container.viewContext.delete(note)
            try container.viewContext.save()
        } catch {
            fatalError("Unable to delete note: \(error)")
        }
    }

    public class func deleteAll(in container: NSPersistentContainer) {
        do {
            let notes = try container.viewContext.fetch(fetchRequest()) as! [Note]
            for note in notes {
                delete(note: note, from: container)
            }
        } catch {
            fatalError("Unable to delete notes: \(error)")
        }
    }

}

注意+CoreDataProperties.swift

import Foundation
import CoreData


extension Note {
    @NSManaged public var text: String
    @NSManaged public var creation: Date

}

谢谢!

4

0 回答 0