1

我无法让具有一对多关系的 Core Data 对象正确地与 DiffableDataSource 一起使用,并且可以使用一些指针。

我有一个表格视图,显示Task从核心数据检索到的对象。我正在使用DiffableDataSource和的组合NSFetchedResultsController。Task 对象经过建模,使其与更多 Task 对象具有一对多的“子任务”关系。表格视图应显示所有父级任务。当一个父任务被点击时,它的子任务应该被插入或从其位置下方的表格视图中删除。

我在didChangeContentWith下面的方法中经历了几种不同的解决方案,但没有达到我想要的结果。目前,我的桌面视图似乎都被打乱了;选择一行会插入重复或不正确的任务。

在此处输入图像描述

起初我认为我的细胞没有为重复使用做好适当的准备,但事实似乎并非如此。我还尝试过仅获取父任务并使用它们对子任务的引用进行插入,添加所有任务并在未展开时删除子任务,以及其他几种方法。

当我查看初始快照和最终差异时,在我的didChangeContentWith方法中,初始快照包含所有任务(和子任务),差异仅包含所需的任务。我不确定我的差异及其对表格视图的应用程序之间发生了什么。我有一种感觉,这与任务对更多任务的引用有关,这些任务不能很好地与 Diffable 一起使用,但我可能只是疯了。

示例数据和逻辑如下:

  {
      title: "Test"
      subtasks: [
          title: "1",
          title: "2",
          title: "3"
      ],
      title: "Foo"
      subtasks: [
          title: "bod",
          title: "bat",
          title: "bar"
      ],
      title: "Bloop"
      subtasks: [
          title: "Blah1",
          title: "Blah2",
          title: "Blah3"
      ]
  }

任务模型:

在此处输入图像描述

的实例化NSFetchedResultsController

    lazy var fetchedResultsController: NSFetchedResultsController<Task> = {
        let fetchRequest: NSFetchRequest<Task> = Task.fetchRequest()
        let nameSort = NSSortDescriptor(key: #keyPath(Task.title), ascending: true)
        let dueDate = NSSortDescriptor(key: #keyPath(Task.dueDate), ascending: false)
        fetchRequest.sortDescriptors = [dueDate, nameSort]
        let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: coreDataStack.managedContext, sectionNameKeyPath: nil, cacheName: "taskMinder")

        fetchedResultsController.delegate = self
        return fetchedResultsController
    }()

数据源的配置:

    func configure(cell: UITableViewCell, for indexPath: IndexPath) {
        guard let cell = cell as? TaskTableViewCell else { return }

        let task = fetchedResultsController.object(at: indexPath)
        cell.set(task: task)
    }

    func configureDataSource() -> UITableViewDiffableDataSource<String, Task> {
        return UITableViewDiffableDataSource(tableView: tableView) { [unowned self] (tableView, indexPath, task) -> UITableViewCell? in
            let cell = tableView.dequeueReusableCell(withIdentifier: TaskTableViewCell.reuseID, for: indexPath)
            self.configure(cell: cell, for: indexPath)
            return cell
        }
    }

最后,我有以下委托方法:

extension TasksViewController: NSFetchedResultsControllerDelegate {
    func controller( _ controller: NSFetchedResultsController<NSFetchRequestResult>,
                     didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {

        // Create diff and go through sections
        var diff = NSDiffableDataSourceSnapshot<String, Task>()
        snapshot.sectionIdentifiers.compactMap { $0 as? String }.forEach { section in
            diff.appendSections([section])

            let tasks = snapshot.itemIdentifiersInSection(withIdentifier: section).compactMap { $0 as?
                NSManagedObjectID }.compactMap {
                    controller.managedObjectContext.object(with: $0) as? Task
            }

            tasks.forEach { task in
                if let parent = task.parentTask, parent.isExpanded {
                    diff.insertItems([task], afterItem: parent)
                } else if task.parentTask == nil {
                    diff.appendItems([task], toSection: section)
                }
            }
        }

        // Apply the diff
        dataSource?.apply(diff)
    }
}

extension TasksViewController: UITableViewDelegate {

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        guard let task = dataSource?.itemIdentifier(for: indexPath) else { return }

        tableView.deselectRow(at: indexPath, animated: true)

        // Hide/show subtasks
        if task.subtasks != nil {
            task.isExpanded.toggle()
            if let cell = tableView.cellForRow(at: indexPath) as? TaskTableViewCell {
                UIView.animate(withDuration: 0.2) {
                    cell.isExpanded = task.isExpanded
                }
            }
        } else {
            // toggle completion status
        }
        self.coreDataStack.saveContext()
    }
}
4

0 回答 0