Search code examples
ioscore-datanspredicatensfetchrequest

NSFetchRequest - Fetch entity from relationship


I have two entities: Alarm and Appointment, which have 1-to-1 relationship.

Now, I would like to retrieve the alarm for a given appointment using NSFetchRequest.

I tried:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:ALARM_ENTITY_NAME];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"forAppointment.objectID = %@", [appointment objectID]];

which throws:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath forAppointment.objectID not found in entity <NSSQLEntity Alarm id=1>'

Does anyone know how I can achieve this?


Solution

  • Simply use

    [NSPredicate predicateWithFormat:@"forAppointment = %@", appointment]
    

    Using the objectID is only necessary if appointment is from a different managed object context. In that case

    [NSPredicate predicateWithFormat:@"forAppointment = %@", [appointment objectID]]
    

    should work. (The right-hand side of == %@ can be a managed object or its object ID. You don't have to specify "objectID" in the predicate itself.)