NSPredicate that references multiple fields on a to-many relationship?

对着背影说爱祢 提交于 2019-12-23 09:39:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!