如何解决NSFetchedResultsController在NSDiffableDataSourceSnapshotReference中将所有实体都退回,即使没有更改
我有一个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)
}
解决方法
我目前正在运行“正在运行的应用程序”。在将新的正在运行的会话结果获取到UITableView时,我曾经遇到过同样的问题。我通过将数据加载到新数组中并在将更改后的数据提取到其中后将旧数组的内容更改为新内容中来解决了该问题。
功能如下:
func loadSessions() -> [Run] {
var _runs : [Run] = []
let context = CoreDataStack.persistentContainer.viewContext
let fetchRequest: NSFetchRequest<Run> = Run.fetchRequest()
fetchRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp",ascending: true),NSSortDescriptor(key: "distance",NSSortDescriptor(key: "duration",ascending: true)]
do {
let sessions = try context.fetch(fetchRequest)
if(sessions.count > 0) {
_runs = sessions
}
} catch {
print("Something happened while trying to retrieve tasks...")
}
return _runs
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。