如何为多个实体创建一个fetchRequest?

时间:2012-04-01 21:15:26

标签: ios

更新以下问题: 我们能够使用fatherChild关系使用父实体获取请求来查询子实体。示例查询如下:

  NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"fatherChild.name LIKE 'fx'"];

现在我们要做的是使用上面的谓词,但是另一个我们想要找到给定父亲名字的孩子的另一个条件。我们使用了以下代码

  NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name LIKE 'john' AND ANY fatherChild.name in 'fx'"];

但程序因异常而崩溃: [__NSCFString countByEnumeratingWithState:objects:count:]:无法识别的选择器发送到实例0xad49c40

通过示例,我们看到我们可以使用子查询,但不确定我们的情况下我们的实例具有一对多关系的语法是什么。任何帮助将不胜感激?

感谢。

问题: 我们有一个包含三个实体的数据模型:父亲,母亲和孩子。请参阅图片以供参考。

我们在父实体上有一个示例查询请求如下:

  NSEntityDescription *entity = [NSEntityDescription entityForName:@"Father"
                                            inManagedObjectContext:managedObjectContext];
  [request setEntity:entity];

  NSString *attributeName = @"name";
  NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"%K like %@",
     attributeName, searchField.text];

我们对母子实体有类似的查询请求。我们想要做的是创建一个查询来组合父和母实体。例如,我们想在单个查询中搜索父亲的姓名=迈克和母亲姓名= Jen。我们怎么做?

感谢您的回复。

1 个答案:

答案 0 :(得分:1)

我们发现我们可以使用SUBQUERY来解决问题。

NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name LIKE %@ AND fatherMother.name LIKE %@ AND (0!=SUBQUERY(fatherChild,$varChild,$varChild.name=%@).@count)",dad.text, mom.text, baby.text];                                 

此处fatherMotherfatherChild是关系名称。

dad.text,mom.text和baby.text是UITextField值。