所以我使用(iOS13)(XCode 13.1) UICollectionViewDiffableDataSource和UITableViewDiffableDataSource。每当我更改CoreData的NSManagedObject中的一个属性时,DiffableAPI都不会捕获它,并自动更改和反应。我怀疑这是因为ManagedObject在执行isEqual操作时没有考虑属性。我不能同时重写托管对象的isEqual函数。我该如何解决这个问题?
发布于 2020-06-24 12:18:57
更新
找到了一个新的解决方案。在再次观看了WWDC2019的Making App with Core Data之后,在处理核心数据时,我们似乎应该使用NSDiffableDataSourceSnapshot<S,I>上的NSDiffableDataSourceSnapshotReference:
let dataSourceReference = UICollectionViewDiffableDataSourceReference(collectionView: collectionView) { collectionView, indexPath, anyObjectID in
guard
let objectID = anyObjectID as? NSManagedObjectID,
let <#myObject#> = managedObjectContext.object(with: objectID) as? <#MyObject#>
else { return nil }
/* dequeue, configure and return cell object here */
}
collectionView.dataSource = dataSourceReference然后,在内容更改时应用快照:
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
dataSourceReference.applySnapshot(snapshot, animatingDifferences: true)
}要手动创建和应用快照,请执行以下操作:
func applySnapshot(animated: Bool) {
let ids = fetchedResultsController.fetchedObjects?.compactMap { $0.objectID as Any } ?? []
let snapshot = NSDiffableDataSourceSnapshotReference()
snapshot.appendSections(withIdentifiers: [<#someSection#>])
snapshot.appendItems(withIdentifiers: ids, intoSectionWithIdentifier: <#someSection#>)
dataSourceReference.applySnapshot(snapshot, animatingDifferences: animated)
}这样做,一切都会像我们预期的那样工作,包括在更改对象的属性时。
我也有同样的问题。在我的例子中,我使用NSFetchedResultsController来接收模型更改。
我的解决方法是将controller(_:didChangeContentWith:)替换为
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>,
didChange anObject: Any,
at indexPath: IndexPath?,
for type: NSFetchedResultsChangeType,
newIndexPath: IndexPath?
) {
if type == .update {
// apply snapshot without animation
} else {
// apply snapshot with animation
}
}以相应地应用新快照。
另一种解决方法是,您不必每次应用时都创建新快照,而是执行以下操作:
这也解决了这个问题,但需要做更多的工作。
我最终还是使用了前一个。
https://stackoverflow.com/questions/61723016
复制相似问题