2012-03-16 164 views
2

我将核心数据模型更改为多对多关系。我相信这是正确的模式。我需要能够做到以下几点:核心数据对多关系问题

(1)一顿饭可以包含许多食品 (2)食品iteme可以链接到许多膳食

enter image description here

我得到以下错误当我尝试拿取所有食物为某一膳食。当它是一对多的时候,这是有效的,但不是因为我把它变成了一对多的关系。

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'to-many key not allowed here' 

- (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:YES]; 
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]]; 
    [fetchRequest setFetchBatchSize:20]; 

    NSFetchedResultsController *theFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.context sectionNameKeyPath:nil cacheName:nil]; 


    self.fetchedResultsController = theFetchedResultsController; 
    _fetchedResultsController.delegate = self; 

    [fetchRequest release]; 
    [theFetchedResultsController release]; 

    return _fetchedResultsController; 
} 

回答

14

就断言需要改变,我认为:

NSPredicate *foodPredicate = [NSPredicate predicateWithFormat:@"ANY meals == %@", self.meal]; 

因为meals现在是一家集。

+0

再次感谢你,解决了这个问题。 – Vikings 2012-03-16 22:40:34

+0

这可能不是你的专业知识,你想介绍一下吗? http://stackoverflow.com/questions/9780864/core-data-insertion-error – Vikings 2012-03-20 03:09:21

+0

如果'餐'与'食物'的关系相反,它不起作用。任何想法如何预测? – iEngineer 2014-05-13 10:32:58