Search code examples
swiftcore-datanspredicate

How to filter using NSPredicate based on if the to many relationship set contains a specific value


I have to two entities. One entity Person, the other Message. For every one Person, there are many messages (so there is a one to many relationship). I need to populate my tableView with Persons, but only Persons which have a set of messages that has at least one message with the attribute sent equalling success.

If what I said is not clear, here is basically what I want:

(obviously this does not compile, I completely made it up for the sake of the question) NSPredicate(Person.messages.contains (sent == "success")

Edit: Forgot to mention that I'm using Core - Data, not just a regular array. I need that NSPredicate for fetched results controller.


Solution

  • "ANY" can be used with a to-many relationship to find the objects for which at least one of the related objects satisfies a condition. In your case:

     NSPredicate(format: "ANY messages.sent == %@", "success")