Search code examples
iosswiftcore-datanspredicate

Core Data NSPredicate: Return all objects which are related to another object whos ID appears in a given array


My object graph looks like this

Servers <-->> Events

Each event entity has an non-optional attribute ID.

An event can only belong to one server, but a server can be related to many events

Given an array of event IDs [1, 2, 3]

I want all the Servers that have an Event who's ID appears in the given array

I tried this but I get 'unable to parse the format string'

NSPredicate(format: "SUBQUERY(events, $event, ANY $event.clientID in %@)", clientIDs as CVarArg)


Solution

  • Try adding an @count to your subquery.

    NSPredicate(format: "SUBQUERY(events, $event, ANY $event.clientID in %@).@count != 0", clientIDs as CVarArg)

    Checkout these docs for bit of a reference. It is for NSExpression but the "Discussion" section has an example of a subquery.