Core Data Predicate To Many
- by Vikings
I have a core data model that has a one to many relationship, there is a category, and it can contain many subcategories.
Category <---- Subcategory
I am trying to perform a fetch that checks if a particular Category contains a Subcategory with a particular name. Let's say I have two categories below, I want to fetch to see if there are any subcategories name "Apple" in the Category named "Fruits".
Vetegables
- Carrot
- Lettuce
Fruits
- Apple
- Orange
- Pear
Code:
- (SubCategory *)searchForSubCategoryWithName:(NSString *)subCategory
inCategory:(Category *)category
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"SubCategory" inManagedObjectContext:self.beer.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c] %@", subCategory];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [self.beer.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects != nil && fetchedObjects.count > 0) {
return [fetchedObjects objectAtIndex:0];
}
else {
return nil;
}
}