Search code examples
objective-ccore-datanspredicatensmanagedobjectnsfetchrequest

Searching CoreData relationships


I'm about to pull my hair out trying to figure out why this isn't working.

I have two entities:

Quote

Customer

A Quote has a one-to-one relationship property with a Customer called simply 'customer'. The Customer has a CoreData objectID (obviously). I am trying to search through all the Quote's and return the one's that have a specific Customer associated with it based off the Customer objectID. Reading through all the tutorials I've managed to get this but I keep getting a crash:

+ (void)fetchQuotesForCustomerID:(NSManagedObjectID*)objectID results:(void(^)(NSError* error, NSArray *fetchedResults))completion {

    NSManagedObjectContext *context = [[QuoteGenerator sharedGenerator] managedObjectContext];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quote"
                                              inManagedObjectContext:context];
    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"customer.objectID == %@", objectID];

    [fetchRequest setPredicate:predicate];

    NSError *error;

    NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];

    if (error) {
        NSLog(@"fetch error = %@", [error localizedDescription]);
        completion(error, nil);
    } else {
        NSLog(@"fetch count = %d", fetchedObjects.count);
        completion(nil, fetchedObjects);
    }
}

Output error:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath customer.objectID not found in entity <NSSQLEntity Quote id=13>'

Is the predicated setup wrong? Reading through the documentation is says that you can use dot syntax to access properties in the predicate.

Please help...


Solution

  • You shouldn't need to do a fetch at all, core data should generate a quotes member on your customer object that will return an NSSet of all the related quote objects.