Padin215
Padin215

Reputation: 7484

NSPredicate for a Core Data Search

I have 3 NSManagedObjets; Person, Stuff, and Collection.

enter image description here

I want to use a NSPredicate to get a list of all Collections that ThePerson has.

Example: Scott has objectA and objectB which are in collection Letters and object1 which is in collection Numbers.

I want to be able to do a fetch request and get back collection Letters and Numbers.

I tried:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY stuffs.persons == %@", person];

And:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SUBQUERY(stuffs, $s, ANY $s.persons == %@)", scott];

Any suggestions?

Upvotes: 0

Views: 143

Answers (2)

Tom Harrington
Tom Harrington

Reputation: 70976

Since it seems that you already have a reference to a ThePerson object, you don't need to do a fetch or use a predicate. You can traverse the relationships you've declared to get the collections. You can get all of the Collections that ThePerson has by using:

NSSet *collections = [person valueForKeyPath:@"stuffs.collections"];

Upvotes: 1

Dave DeLong
Dave DeLong

Reputation: 243156

Your SUBQUERY syntax is wrong (for a full explanation, see this answer or this answer). It should be something like:

SUBQUERY(stuffs, $s, ANY $s.persons == %@).@count > 0

Upvotes: 1

Related Questions