首页 > 解决方案 > One object in multiple sections when sorting with NSFetchedResultsController

问题描述

I’ve just started using Core Data and NSFetchedResultsController and I'm kind of stuck. I've a Book entity which has a category attribute of type String. The data is loaded into a collection view and grouped by sections based on this category. All’s working fine this way, but the problem is that a Book should be able to appear in multiple categories (and collection view sections). I could change the category’s type to an Array of String, but how would I do the sorting then?

let request = Book.fetchedRequest() as NSFetchRequest<Book>
let categorySort = NSSortDescriptor(key: #keyPath(Book.category)), ascending:true)
request.sortDescriptors = [categorySort]

do {
fetchedResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: #keyPath(Book.category)), cacheName: nil) 
try fetchedResultsController.performFetch()
} catch let error as NSError {
print(“Could not fetch. \(error), \(error.userInfo)”)
}

Should I just give up on using NSFetchedResultsController or is it possible to make this work?

标签: iosswiftcore-datansfetchedresultscontrollercollectionview

解决方案


...一本书应该能够出现在多个类别(和收藏视图部分)中。

我应该放弃使用 NSFetchedResultsController 还是可以让它工作?

您描述的内容无法通过获取的结果控制器实现。 NSFetchedResultsController获取所有获取的对象(可能由谓词过滤),根据排序描述符对它们进行排序,并根据sectionNameKeyPath参数对它们进行分组。

获取的结果控制器不可能多次提供相同的对象(在相同或不同的部分)。


推荐阅读