问题
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 Den
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:
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"];
来源:https://stackoverflow.com/questions/3664358/nspredicate-that-references-multiple-fields-on-a-to-many-relationship