【发布时间】:2021-01-30 17:54:45
【问题描述】:
我有一个 NSFetchedResultsController 来监控与其他实体耦合的实体。现在在 UICollectionView 中显示实体时,我使用 UICollectionViewDiffableDataSource。
问题在于,当更改 1 个实体时,快照会返回所有项目,并且不仅会刷新更新的实体,还会刷新所有实体。我可以做些什么来防止刷新没有变化的项目?
FetchedResultsController
class func fetchResultsController(template: Template, context: NSManagedObjectContext) -> NSFetchedResultsController<Counters> {
let fetchRequest: NSFetchRequest<Counters> = Counters.fetchRequest()
fetchRequest.sortDescriptors = [
NSSortDescriptor(key: #keyPath(Counters.name), ascending: true)
]
fetchRequest.predicate = NSPredicate(format: "%@ = %K", argumentArray: [template, #keyPath(Counters.template)])
let fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest,
managedObjectContext: context,
sectionNameKeyPath: nil,
cacheName: nil)
return fetchResultController
}
委托
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
var diff = NSDiffableDataSourceSnapshot<String, CounterCellViewModel>()
snapshot.sectionIdentifiers.forEach { section in
diff.appendSections([section as! String])
let items = snapshot.itemIdentifiersInSection(withIdentifier: section)
.map { (objectId: Any) -> CounterCellViewModel in
let oid = objectId as! NSManagedObjectID
let object = controller.managedObjectContext.object(with: oid) as! Counters
return CounterCellViewModel(counter: object)
}
diff.appendItems(items, toSection: section as? String)
self.countersDataSource.apply(diff, animatingDifferences: false)
}
}
数据源
private lazy var countersDataSource: UICollectionViewDiffableDataSource<String, CounterCellViewModel> = {
return UICollectionViewDiffableDataSource(collectionView: self.collectionView) { [unowned self] (collectionView, indexPath, viewModel)
-> UICollectionViewCell? in
let cell = collectionView.deo_dequeueReusableCell(ofType: CounterCell.self, for: indexPath)
cell.viewModel = viewModel
return cell
}
}()
CounterCellViewModel 可散列
func hash(into hasher: inout Hasher) {
hasher.combine(self.counter.id)
}
【问题讨论】:
标签: ios swift core-data nsfetchedresultscontroller