NSFetchedResultsController的sections数组元素的名称未正确更新

时间:2017-05-10 22:50:55

标签: ios swift core-data nsfetchedresultscontroller

我有一个NSFetchedResultsController的简单用法定义类似这个人为的例子

let request: NSFetchRequest<StudentEntity> = StudentEntity.fetchRequest()
  request.sortDescriptors = [
    NSSortDescriptor(key: "class.name", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare(_:)))
  ]

fetchedResultsController = NSFetchedResultsController<StudentEntity>(
    fetchRequest: request,
    managedObjectContext: context,
    sectionNameKeyPath: "class.name",
    cacheName: nil)

这有助于表格视图显示按类别关系设置的类别分组的学生实体。类实体具有name属性,因此sectionNameKeyPath是class.name。

当用户对学生引用的类进行编辑时,我尝试重新加载表中的数据但不幸的是我发现我正在使用的部分名称没有更新。大量的调试显示类实体当然正在更新,但由于某种原因,section [] .name没有更新。我更新了类名,如下所示

classEntity.name = newClassName

do
{
  try context.save()
}
catch let error
{
  dbgLog("failed to save context; error=\(error)")
}

tableView.reloadData();

这导致以下数据源方法正确运行

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
  let sectionInfo = fetchedResultsController!.sections![section]
  let sectionTitle = sectionInfo.name
  let sectionStudentEntity = sectionInfo.objects![0] as! StudentEntity
  let sectionTitleFromStudent = sectionStudentEntity.class!.name!

但是sectionTitle不会更新并显示旧的类名,其中sectionTitleFromStudent正确显示更新的新类名。

我认为这是因为sectionNameKeyPath是一个嵌套路径,虽然类实体正在更新,但fetchedResultsController以某种方式检测不到学生实体本身的任何变化,因此不会重新创建这些部分名称。感觉就像一个bug,但幸运的是我可以使用正确更新的sectionTitleFromStudent字符串解决它。

任何人有任何想法,或者自己遇到过同样的问题?

干杯

1 个答案:

答案 0 :(得分:2)

FetchedResultsController将仅观察对其获取的实体(在您的Student个对象中)的对象的更改。因此,它不知道相关Class对象的属性的更改。要使其知道,您可以重做performFetch,它应该触发它以更新其获取的对象和部分。 (请注意,performFetch会绕过正常的FRC更改跟踪,因此FRC委托方法不会触发,但这不应该是一个问题,因为无论如何你都在tableView上做了一个完整的reloadData

相关问题