views:

25

answers:

1

I'm using a SQLite persistent store. I have a NSManagedObject class Den with a to-many relationship Bear. Bear has several fields:

Bear:
    breed
    color
    age
    ...

When I am building fetch requests for my Foo objects, I can filter to objects that have a related Bear with a certain field value:

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

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

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

But is there any way to search for a Den that has a bear that is both brown and a grizzly? The following is legal, but incorrect, 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'"];
+1  A: 

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

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

Barry Wark
The Core Data documentation leaves me... frustrated at times. This is perfect.
Seamus Campbell
I've pointed many folks to the `NSExpression` documentation. Please file a bug report at bugreporter.apple.com on the documentation and suggest how it might have been presented so that you could have found it sooner.
Barry Wark