I am using Core Data in my application where I am trying to retrieve entities whose relationship objects attribute match my criteria. Unfortunately I am stuck here, because I am passing the id for the relationship object, but I am getting an error saying that the criteria I am passing is not being recognized as an attribute of the entity I am querying.
This is true, because my criteria is actually an attribute for the relationship object, and not an attribute of the entity that I am querying itself. How do I achieve this?
Here is my code:
// Create fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:myEntityName inManagedObjectContext:context];
[fetchRequest setEntity:entity];
// Create predicate
NSPredicate *pred = [NSPredicate predicateWithFormat:@"relationshipObjectId == %@", relationshipObjectId];//This is where I am having trouble
[fetchRequest setPredicate:pred];
NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
if ([items count]>0) {
return items[0];
} else {
return nil;
}
Can anyone see what it is I am doing wrong?
To find all related objects whose attribute matches a certain value, you would use a predicate like
[NSPredicate predicateWithFormat:@"rel.attr == %@", value]
where "rel" is the name of the relationship, and "attr" is the name of the attribute that should match the value.