Search code examples
ioscore-datansmanagedobjectnsfetchrequest

Core Data: Fetching related objects in many-to-many relationship


I'm trying to wrap my head around the proper architecture/pattern for this situation:

I've got two entities, Book and Librarys. They each have a many-to-many relationship to the other (Books can be in many Librarys, and a Library will have many Books.

One of my views lists books in a particular library. I have a controller class that handles fetching of this data and provides it to my view. To do that, I'm planning on using an NSFetchRequest for all Book entities, filtered by a predicate that fetches only books in a specific Library. But I can't seem to find the proper way to format the predicate for this fetch request.

I also investigated simply accessing Library's books accessor to get access to the appropriate books without having to fetch anything (as described here), but I want to use NSFetchedResultsControllerDelegate so my controller is notified about any changes to the fetched objects, and can notify the view. I considered just listening for NSManagedObjectContextDidChangeObjectsNotification, but this will deliver notifications for every single change in the context, even if it's not for relevant entities.

How have you handled situations like this in the past?


Solution

  • Your fetch request / predicate could look something like this:

    let fetchRequest: NSFetchRequest<Book> = Book.fetchRequest()
    fetchRequest.predicate = NSPredicate(format: "%K CONTAINS %@", #keyPath(Book.libraries), library)
    
    // Another option:
    fetchRequest.predicate = NSPredicate(format: "SELF IN %@", library.books!)