当我有两个实体Parent和Child( - “children”之间的关系,inverse - “parent”)时,很容易得到具体父级的子代,请参阅下面的代码:
Parent *parent = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Child" inManagedObjectContext:context]];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[request setSortDescriptors:@[sort]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(parent == %@)", parent]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(@"results :%@", results);
是的,当然,我可以让孩子没有 NSFetchRequest ,但在我的情况下,我必须这样做; 好吧,我的麻烦在于我只有一个实体,例如“父母”(关系 - “父母”,反向 - “父母”); 和一位家长有另外3个父母; 如何让所有父母具体的父母;我试着这样做:
Parent *parent = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Parent" inManagedObjectContext:context]];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[request setSortDescriptors:@[sort]];
[request setPredicate:[NSPredicate predicateWithFormat:@"(parents == %@)", parent]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(@"results :%@", results);
但是我的程序程序崩溃了: 由于未捕获的异常'NSInvalidArgumentException'而终止应用,原因:'此处不允许使用多对键'
答案 0 :(得分:4)
即使您只有一个实体,也需要定义两个关系:
并使它们彼此成反比关系。然后
[NSPredicate predicateWithFormat:@"(parent == %@)", parent]
应该按预期工作。