Search code examples
swiftcore-datansfetchedresultscontroller

Swift Core Data NSPredicate


What Am I Trying to Accomplish?

I have an app with three Core Data entities: Ingredients, Cookies, and CookieIngredients.

  • Ingredients are eggs, milk, butter, etc. and a Bool indicating whether I have that ingredient in my kitchen.
  • Cookies are chocolate chip, oatmeal raisin, etc.
  • CookieIngredients are the units of each ingredient required for each cookie.

I want to be able to display which cookies I can make based on which ingredients I have indicated are in my kitchen.

What Have I Done?

I've successfully gotten my app to a state where all of these entities are managed in Core Data and I'm able to flag ingredients as "in my kitchen" with no problem. I'm able to search on Cookies based on ingredients and title.

Where Am I Stuck?

I've been unable to find any examples to help understand how to create an NSPredicate to limit my FetchedResultsController to only Cookies where all of the CookieIngredient's Ingredients are "in my kitchen". If this was a web application using a MySQL database, I'd be able to do this with some inner joins, but I have no idea how to achieve something similar -- or even if it's possible to do such a thing -- with Core Data.


Solution

  • Solution!

    Here's the predicate that worked for me:

    NSPredicate(format: "SUBQUERY(cookieIngredients, $X, $X.in_kitchen == true).@count == cookieIngredients.@count")