Search code examples
ioscore-datanspredicatensfetchedresultscontrollernsfetchrequest

Core Data: How to fetch Entities based on an attribute of a related entity


This is what the pertinent part of my object graph looks like:

[Anime] <->> [AnimeName @string @type]

So an Anime object has many AnimeName objects that contain a string and the type of name they are. Now to implement a "Search by Name" feature, I would need a predicate that matches all Anime entities where any name contains the search string. What I have tried so far is this:

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Anime"];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"names.string == %@", searchString]];

on an NSFetchRequest of Anime entities, this however gives the following error:

"NSInvalidArgumentException", "to-many key not allowed here"

Which makes perfect sense to me, and I could simply work around that by using this:

NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"AnimeName"];
[fetch setPredicate:[NSPredicate predicateWithFormat:@"string == %@", searchString]];

and then getting the relationship to the Anime entity from each returned object, but then how do I plug that into an NSFetchedResultsController for my UITableView?

Please help if anyone knows a solution.


Solution

  • For to-many relationships, use "ANY":

    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Anime"];
    [fetch setPredicate:[NSPredicate predicateWithFormat:@"ANY names.string == %@", searchString]];