我用到一个核心数据模型,一对多关系模式。其中一个category,包含很多subcategories。
Category <---->> Subcategory
我想做到,判断指定的Category中是否包括具体名称的Subcategory。
比如,现在已经有两个category,需要得知命名为Fruit的category中是否包括名为Apple的subcategory。
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;
}
}
我不清楚你的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;
}
}
也可以添加category到predicate中,需要在subcategory管理对象定义:
- (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;
}
}
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。