我有一个具有一对多关系的核心数据模型,有一个类别,它可以包含许多子类别。
类别 <---->> 子类别
我正在尝试执行检查特定类别是否包含具有特定名称的子类别的提取。假设我在下面有两个类别,我想查看名为“Fruits”的类别中是否有任何子类别名称为“Apple”。
Vetegables
- Carrot
- Lettuce
Fruits
- Apple
- Orange
- Pear
代码:
- (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;
}
}