更新以下问题: 我们能够通过父子关系使用父实体获取请求来查询子实体。示例查询如下:
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"fatherChild.name LIKE 'fx'"];
现在我们要做的是使用上面的谓词,但我们想要找到给定父亲姓名的 child 的另一个条件。我们使用了以下代码
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"name LIKE 'john' AND ANY fatherChild.name in 'fx'"];
但是程序崩溃了异常: [__NSCFString countByEnumeratingWithState:objects:count:]: 无法识别的选择器发送到实例 0xad49c40
通过阅读示例,我们看到我们可以使用子查询,但不确定在我们有一个具有一对多关系的实体的情况下,语法是什么。任何帮助将不胜感激?
谢谢。
问题: 我们有一个包含三个实体的数据模型:父亲、母亲和 child 。请查看图片以供引用。
下面给出了我们对父实体的查询请求示例:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Father"
inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSString *attributeName = @"name";
NSPredicate *myPredicate = [NSPredicate predicateWithFormat:@"%K like %@",
attributeName, searchField.text];
我们对 Mother 和 Child 实体有类似的查询请求。我们想要做的是创建一个查询来组合 Father 和 Mother 实体。例如,我们想在单个查询中搜索 Father's name = Mike 和 Mothers name = Jen。我们如何做到这一点?
感谢您的回复。
最佳答案
我们发现我们可以使用 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];
这里 fatherMother
和 fatherChild
是关系的名称。
dad.text、mom.text 和 baby.text 是 UITextField
值。
关于ios - 如何为多个实体创建一个 fetchRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9968413/