Search code examples
iosswiftcore-datansfetchedresultscontrollercollectionview

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?


Solution

  • ... a Book should be able to appear in multiple categories (and collection view sections).

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

    What you describe cannot be achieved with a fetched results controller. NSFetchedResultsController takes all fetched objects (which are possibly filtered by a predicate), sorts them according to the sort descriptors, and groups them according to the sectionNameKeyPath argument.

    There is no way that a fetched results controller provides the same object multiple times (in the same or in different sections).