Search code examples
ioscore-datanspredicatensfetchrequest

iOS: core data, number of relationship with Auto ID


I have two Entities: Woods and Tree

Woods has a relationship with Tree because a woods can have many trees. Ok it's easy.

In my app I know the id of one woods (the auto id: NSManagedObjectID) and I want to know how many tree has my woods.

My code is:

NSFetchRequest *req = [NSFetchRequest fetchRequestWithEntityName:@"Tree"];
        [req setPredicate:[NSPredicate predicateWithFormat:@"wood.self == %@", [self app].current_wood_id]];
        [req setResultType:NSCountResultType];
        NSUInteger total = [context countForFetchRequest:req error:&error];
        NSLog(@"total:%d", (int)total);

but It doesn't work, why?


Solution

  • You should stop thinking in IDs and instead embrace the object graph. The IDs you are abusing to identify objects are not there for this purpose (but for identifying object across threads).

    The relationship in a predicate is written just like an attribute:

    [NSPredicate predicateWithFormat:@"wood = %@", aWoodInstance];
    

    In you specific case, you do not need a fetch request. Just write:

    wood.trees.count
    

    It could not be easier! See how powerful the object graph is?