我用到一個核心數據模型,一對多關系模式。其中一個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;
}
}