Core Data Predicate To Many
Posted
by
Vikings
on Stack Overflow
See other posts from Stack Overflow
or by Vikings
Published on 2012-10-31T22:35:50Z
Indexed on
2012/10/31
23:00 UTC
Read the original article
Hit count: 205
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;
}
}
© Stack Overflow or respective owner