Navigating the Core Data Object Graph [2]

前端 未结 2 868
遥遥无期
遥遥无期 2021-01-24 07:11

I asked a question yesterday where I really should have started with a simpler example. Having distilled my question to the basics, I\'ve managed to solve my problem using exis

2条回答
  •  北海茫月
    2021-01-24 07:47

    I've never tried to use a subquery before, that's very cool and good to see an example of it. You should add the solution as an answer to the question actually!

    I would have probably done as Abizern suggested, since this is a tree-like hierarchy and its easier to traverse up the tree using to-one relationships.

    In code this looks like:

    NSManagedObjectContext *moc = APPDELEGATE.managedObjectContext;
    NSFetchRequest *request = [NSFetchRequest new];
    [request setEntity:[NSEntityDescription entityForName:@"EntityC" inManagedObjectContext:moc]];
    [request setPredicate:[NSPredicate predicateWithFormat:@"tag = YES"]];
    NSError *fetchError = nil;
    NSArray *children = [moc executeFetchRequest:request error:&fetchError];
    

    children is an array of EntityC objects that match the predicate. The next step is getting a set of unique EntityA objects that are the "grandparents" of these. We can take advantage of key-value coding here:

    NSArray *grandParents = [children valueForKeyPath:@"parent.@distinctUnionOfObjects.parent"];
    

    In this case, for efficiency, we'd probably want to prefetch the parent.parent keypath during our initial fetch request:

    [request setRelationshipKeyPathsForPrefetching:@[@"parent.parent"]];
    

    Hope this helps!

提交回复
热议问题