Ben*_*Ben 6 iphone core-data objective-c nspredicate
这是我的模型:http: //www.girardet.ch/model.png
我的目标是使用这些标准检索所有引号:
这是我的代码:
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ThemeEntries" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor1 = [[NSSortDescriptor alloc] initWithKey:@"relevancy" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor1, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// predictate - filter
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"theme.name_en=%@ AND quotes.author.alias=%@",@"mytheme", @"myauthor"];
Run Code Online (Sandbox Code Playgroud)
[fetchRequest setPredicate:predicate];
我得到"to-many key not here here"错误.
如果我改为使用这个谓词
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"theme.name_en=%@, @"mytheme"];
Run Code Online (Sandbox Code Playgroud)
它运作良好,我可以循环ThemeEntries我获得并得到我的所有报价...但它不是由作者过滤.
我可以做些什么来过滤作者?
Tec*_*Zen 26
你的问题是你的一个keypath的关系是to-many,to-many,而谓词不知道哪个特定对象与哪个.
你有ThemeEntities<<-->>Quotes哪一个在每一端产生一套.该quotes.author.alias的keyPath说,"一套报价情况,每个挂笔者实例这反过来又一个别名属性." 谓词无法处理集合.
您需要使用子查询来跳转到多个键路径.子查询本质上是一个嵌套谓词,它搜索一个集合并返回与嵌套谓词匹配的另一组对象.子查询的文档很少,但它们的格式如下:
SUBQUERY(collectionName,$collectionElementVariable,expression-with-$collectionElementVariable)
Run Code Online (Sandbox Code Playgroud)
在这种情况下,您正在查找具有与所提供字符串匹配的别名的作者关系的任何引用实例.你的谓词需要看起来像:
@"theme.name_en=%@ AND (0!=SUBQUERY(quotes,$eachQuote,$eachQuote.author.alias=%@).@count)",@"mytheme", @"myauthor"
Run Code Online (Sandbox Code Playgroud)
子查询说,"在引用集中,取每个引用对象并测试其作者关系对象是否具有与'myauthor'匹配的别名属性.计算具有该匹配的引用对象的数量.如果该数字不为零,则返回真正."
每当您跨越多对多关系的密钥路径时,您都需要使用子查询.