首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >更改NSManagedObject的属性值不会反映在DiffableDataSource上

更改NSManagedObject的属性值不会反映在DiffableDataSource上
EN

Stack Overflow用户
提问于 2020-05-11 13:41:45
回答 1查看 107关注 0票数 0

所以我使用(iOS13)(XCode 13.1) UICollectionViewDiffableDataSourceUITableViewDiffableDataSource。每当我更改CoreDataNSManagedObject中的一个属性时,DiffableAPI都不会捕获它,并自动更改和反应。我怀疑这是因为ManagedObject在执行isEqual操作时没有考虑属性。我不能同时重写托管对象的isEqual函数。我该如何解决这个问题?

EN

回答 1

Stack Overflow用户

发布于 2020-06-24 12:18:57

更新

找到了一个新的解决方案。在再次观看了WWDC2019的Making App with Core Data之后,在处理核心数据时,我们似乎应该使用NSDiffableDataSourceSnapshot<S,I>上的NSDiffableDataSourceSnapshotReference

代码语言:javascript
复制
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

然后,在内容更改时应用快照:

代码语言:javascript
复制
func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChangeContentWith snapshot: NSDiffableDataSourceSnapshotReference) {
  dataSourceReference.applySnapshot(snapshot, animatingDifferences: true)
}

要手动创建和应用快照,请执行以下操作:

代码语言:javascript
复制
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:)替换为

代码语言:javascript
复制
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
  }
}

以相应地应用新快照。

另一种解决方法是,您不必每次应用时都创建新快照,而是执行以下操作:

  • 最初,在接收到模型更新时,创建新快照并将其应用于数据源
  • ,向数据源请求现有快照并通过计算差异对其进行修改,然后将其应用于数据源

这也解决了这个问题,但需要做更多的工作。

我最终还是使用了前一个。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61723016

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档