Search code examples
swiftmacoscore-datansfetchedresultscontrollernsfetchrequest

NSFetchedResultsController fetchRequest for one-many relationship


I would really appreciate some help with using NSFetchResultsController. I think what I am need to do should be simple for some people, but I am a bit stuck!

I will try to explain what I am doing, or a simplified version of it. I have 2 viewControllers, each displaying an NSTableView. I am using Core Data, with an entity Clubs. One of the viewControllers displays a list of Clubs. So for this one, I create an NSFetchResultsController, passing to it a fetchRequest which is basically NSFetchRequest<Clubs>(entityName: “Clubs”).

Each club has a list of Members, with a one-many relationship). I want to display the members using the 2nd viewController. So when I tap a club in the first table, I want the second table to show its members.

I have an NSFetchResultsController connected to the second table. I am stuck at what fetchRequest to send to it. If I use a similar one to the first, i.e. NSFetchRequest<Members>(entityName: “Members”), as expected, I end up with one table showing all of the clubs stored, and the second table showing ALL members stored, whereas I want only the members in the club selected in the first table. I hope that makes sense. So my question is, what fetchRequest should I send to the 2nd tables NSFetchResultsController?


Solution

  • You should add the following predicate to the fetch request underlying the FRC:

    fetchRequest.predicate = NSPredicate(format:"club == %@", theClubSelectedInTheFirstViewController)