2012-03-16 146 views
1

好的,我在核心数据中有一对多的关系。一顿饭可以由许多不同的食物组成。我的代码在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; 
} 
+0

我看了看你的NSFetchedResultsController代码,找不到任何问题。无论“self.meal”包含什么,错误行为是否发生?当你看到虚假的数据时,“self.meal”不存在,对吧?或者,您是否可以在之前的代码实验遗留下来的持久存储中存在虚假数据?如果是这样,手动删除存储文件可以帮助。 – FluffulousChimp 2012-03-16 03:01:19

+0

我必须遍历每行代码,但我确实相信self.meal永远不会变为零 – Vikings 2012-03-16 03:08:34

+1

您可以粘贴更多的代码吗?这里似乎没有任何问题。 – 2012-03-16 04:17:12

回答

1

如果self.mealsnil那么NSFetchedResultsController将返回Food S中的不是Meal的一部分,从而占你发现的行为。

0

您的谓词不正确。您不应该将meals(这是Meal对象的NSSet)与单个meal进行比较。您需要查看在Food对象上设置的meals是否包含该餐。

[NSPredicate predicateWithFormat:@"%@ in meals", self.meal] 
+0

我继续尝试了这一点,但没有奏效。感谢您的输入。 – Vikings 2012-03-16 14:19:33