对许多人的核心数据谓词
Posted
技术标签:
【中文标题】对许多人的核心数据谓词【英文标题】:Core Data Predicate To Many 【发布时间】:2012-10-31 22:35:50 【问题描述】:我有一个核心数据模型,它具有一对多关系,有一个类别,它可以包含许多子类别。
类别 > 子类别
我正在尝试执行获取,以检查特定类别是否包含具有特定名称的子类别。假设我下面有两个类别,我想获取名称为“水果”的类别中是否有名称为“苹果”的子类别。
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;
【问题讨论】:
:) 这对我来说看起来不错,所以你的问题是什么? NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c] %@ and category == %@", subCategory, category]; 【参考方案1】:尝试寻找具有您喜欢的子类别的类别实体,而不是相反,然后从结果中返回 category.subcategory。我不确定你的 NSManagedObjects 是什么样子,但试试这个:
- (SubCategory *)searchForSubCategoryWithName:(NSString *)subCategory
inCategory:(Category *)category
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.beer.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"subcategory.name == [c] %@ AND name == %@", subCategory, category.name];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray *fetchedObjects = [self.beer.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects != nil && fetchedObjects.count > 0)
Category *categoryManagedObject = [fetchedObjects objectAtIndex:0];
return categoryManagedObject.subcategory;
else
return nil;
...或者只是将类别添加到您的谓词中,您应该将它包含在您的子类别托管对象定义中:
- (SubCategory *)searchForSubCategoryWithName:(NSString *)subCategory
inCategory:(Category *)category
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Category" inManagedObjectContext:self.beer.managedObjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == [c] %@ AND category == %@", subCategory, category];
[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;
【讨论】:
以上是关于对许多人的核心数据谓词的主要内容,如果未能解决你的问题,请参考以下文章