NSPredicate that references multiple fields to many relationships?

I use SQLite persistent storage. I have an NSManagedObject class Den with a to-many Bear relation. Bear has several fields:

 Bear: breed color age ... 

When I create select queries for my Den objects, I can filter objects that have a Bear associated with a specific field value:

 NSPredicate *hasGrizzlyPred = [NSPredicate predicateWithFormat:@"ANY Bear.breed == 'grizzly'"]; 

Or I can just as easily find Den that has a brown bear:

 NSPredicate *hasBrownBearPred = [NSPredicate predicateWithFormat:@"ANY Bear.color == 'brown'"]; 

But is there a way to find Den with a bear that is brown and grizzly? The following is right, but false, I think:

 // Not quite right: search for a den with a brown bear AND a grizzly NSPredicate *hasBrownAndGrizzlyPred = [NSPredicate predicateWithFormat:@"ANY Bear.color == 'brown' AND ANY Bear.breed == 'grizzly'"]; 
+6
objective-c iphone core-data nspredicate
source share
1 answer

You can do this using the SUBQUERY predicate expression. In the case of a query for dens with a bear (where Den is related to-many to Bear named bears ), which is both brown and grizzly:

[NSPredicate predicateWithFormat:@"SUBQUERY(bears, $b, $b.color=='brown' AND $b.breed=='grizzly') .@count > 0"];

+6
source share

All Articles