我的核心数据模型中存在一对多关系。一顿饭可以有多种食物。我想在一张桌子上放满一顿饭的食物。因此,如果第一餐中有苹果,橙子和柠檬,则餐桌上将包含这三种食物。
非常感谢您的帮助,因为我完全被卡住了。
这是我的模型:
和NSManagedObject类:
餐时
@class Food;
@interface Meal : NSManagedObject
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSSet *foods;
@end
@interface Meal (CoreDataGeneratedAccessors)
- (void)addFoodsObject:(Food *)value;
- (void)removeFoodsObject:(Food *)value;
- (void)addFoods:(NSSet *)values;
- (void)removeFoods:(NSSet *)values;
@end
食物
@class Meal;
@interface Food : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Meal *meals;
@end
这是我尝试尝试的代码,但是我遇到了一些问题。
- (NSFetchedResultsController *)fetchedResultsController
{
if (_fetchedResultsController != nil)
return _fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Food" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"Meal.foods == %@", entity]];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
[fetchRequest release];
[theFetchedResultsController release];
return _fetchedResultsController;
}
最佳答案
您提到自己遇到了问题,但不是问题所在。但是您的NSFetchRequest
谓词对我而言并不正确。同样,在meals
上定义的Food
是复数形式,但关系是一对一-有点令人困惑。
您的UITableView应该使用单个Food
中的Meal
填充,对吗?让我们将其称为Meal
_thisMeal
,然后获取谓词应为:
NSPredicate *foodPredicate = [NSPredicate predicateWithFormat:@"meals == %@",_thisMeal];
[fetchRequest setPredicate:foodPredicate];
因此,您要获取的实体是
Food
;并且此谓词可确保其meals
属性是您的UITableViewController要查找的Meal
。更新以显示如何获取命名的
Meal
要获取名为“自定义餐”的
Meal
,请执行以下操作:Meal *_thisMeal = nil;
// this assumes that there should be only one Meal named "Custom Meal"
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Meal"];
NSPredicate *fetchPredicate = [NSPredicate predicateWithFormat:@"name = %@",@"Custom Meal"];
NSError *fetchError = nil;
NSArray *meals = [_context executeFetchRequest:request error:&fetchError];
if( fetchError )
NSLog(@"%s - ERROR while fetching Meal: %@,%@",__FUNCTION__,fetchError,[fetchError userInfo]);
else if( [meals count] != 0 )
_thisMeal = [meals objectAtIndex:0];