Core Data: Query objectIDs in a predicate?

Michael Waterfall picture Michael Waterfall · Jun 2, 2009 · Viewed 23.3k times · Source

I am fetching a set of objects from a Core Data persistent store using a fetch request and a predicate. My current predicate simply checks whether an attribute is >= a certain value. This all works great, except that I want to finally exclude any objects that are currently held in an array.

I basically need to be able to exclude a set of objects, and the only way I think I can do this is to be able to get a list of objectID from my managed objects array, and create another expression in my predicate to ensure that any objects returned don't have the same objectID. I.E.@"ANY records.objectID NOT IN %@", arrayOfObjectID.

How can I do this?

Answer

Barry Wark picture Barry Wark · Jun 2, 2009

A predicate like

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"NOT (self IN %@)", arrayOfExcludedObjects];

where the entity of the fetch request is the entity of objects in the array, should do what you want. This can, of course be combined with other clauses in a single predicate for a fetch request.

In general, object comparisons (e.g self == %@ or self IN %@) compare on objectID in Core Data queries. The argument can either be an NSManagedObject instance or an NSMangedObjectID instance. So the predicate format above could take arrayOfExcludedObjects or [arrayOfExcludedObjects valueForKey:@"objectID"] as the argument.