如何从 iOS 13 中的 NSFetchResultsController 获取可区分的快照? [英] How to get a diffable snapshot from an NSFetchResultsController in iOS 13?

查看:9
本文介绍了如何从 iOS 13 中的 NSFetchResultsController 获取可区分的快照?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我们在 WWDC 2019 视频 230 中,从大约 14 分钟开始,据称 NSFetchedResultsController 现在提供 NSDiffableDataSourceSnapshot,因此我们可以将其直接应用于可区分的数据源 (UITableViewDiffableDataSource).

So here we are in WWDC 2019 video 230, and starting at about minute 14 it is claimed that NSFetchedResultsController now vends an NSDiffableDataSourceSnapshot, so we can just apply it directly to a diffable data source (UITableViewDiffableDataSource).

但这并不完全是他们所说的,或者我们得到的.我们在委托方法 controller(_:didChangeContentWith:) 中得到的是一个 NSDiffableDataSourceReference.我们如何从中获取实际快照,我的可区分数据源泛型类型应该是什么?

But this is not quite what they say, or what we get. What we get, in the delegate method controller(_:didChangeContentWith:), is an NSDiffableDataSourceReference. How do we get from this to an actual snapshot, and what should my diffable data source generic types be?

推荐答案

diffable 数据源应该用泛型类型 String 和 NSManagedObjectID 声明.现在您可以将引用转换为快照:

The diffable data source should be declared with generic types String and NSManagedObjectID. Now you can cast the reference to a snapshot:

func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
    let snapshot = snapshot as NSDiffableDataSourceSnapshot<String,NSManagedObjectID>
    self.ds.apply(snapshot, animatingDifferences: false)
}

这留下了您将如何填充单元格的问题.在 diffable 数据源中(在我的示例中为 self.ds),当您填充单元格时,返回到 fetched results 控制器并获取实际数据对象.

This leaves open the question of how you're going to populate the cell. In the diffable data source (self.ds in my example), when you populate the cell, return to the fetched results controller and fetch the actual data object.

例如,在我的表格视图中,我在每个单元格中显示一个组的 name:

For example, in my table view I am displaying the name of a Group in each cell:

lazy var ds : UITableViewDiffableDataSource<String,NSManagedObjectID> = {
    UITableViewDiffableDataSource(tableView: self.tableView) {
        tv,ip,id in
        let cell = tv.dequeueReusableCell(withIdentifier: self.cellID, for: ip)
        cell.accessoryType = .disclosureIndicator
        let group = self.frc.object(at: ip)
        cell.textLabel!.text = group.name
        return cell
    }
}()

这篇关于如何从 iOS 13 中的 NSFetchResultsController 获取可区分的快照?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆