好的,我在核心数据中有一对多的关系。一顿饭可以包含许多不同的食物。我的代码在Fetch Controller中似乎不太正常。我可以自信地说,self.meal是我正在尝试获取的当前餐点。我正在整个应用程序中共享上下文。
我遇到的问题是该应用程序正在显示食物,但似乎与膳食中的内容并不完全匹配。一旦添加食物,即使它不在餐内,它也会立即显示出来。
任何帮助或建议,我都在正确地执行此操作。
- (NSFetchedResultsController *)fetchedResultsController
{
self.context = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Food" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
NSPredicate *foodPredicate = [NSPredicate predicateWithFormat:@"meals == %@", self.meal];
[fetchRequest setPredicate:foodPredicate];
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.context sectionNameKeyPath:nil cacheName:@"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
[fetchRequest release];
[theFetchedResultsController release];
return _fetchedResultsController;
}
最佳答案
如果self.meals
是nil
,则NSFetchedResultsController
将返回不属于Food
的Meal
,从而说明您注意到的行为。