nburk
nburk

Reputation: 22731

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?

Upvotes: 0

Views: 355

Answers (2)

Hal Mueller
Hal Mueller

Reputation: 7646

If you have a 1-1 relationship between the two (and if you've implemented NSManagedObject subclasses for your entities), there's no need for a fetch. Just walk the keypath:

Alarm *alarm = appointment.alarm;

Or, if you're working with primitive NSManagedObject

NSManagedObject *alarm = [appointment valueForKeyPath:@"alarm"];

Upvotes: 0

Martin R
Martin R

Reputation: 539685

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

Upvotes: 1

Related Questions