1

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...

4

2 回答 2

3

Turns out a lack of sleep and @Gary lead me to the right answer.

  1. I should have had a to-many relationship from customer to Quote.

  2. When comparing an entities NSManagedObjectID property you don't have to explicitly state it. So the following modification to the NSPredicate fixed my issue.

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

于 2013-02-26T05:47:53.910 回答
1

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.

于 2013-02-26T05:51:28.577 回答