2012-03-16 221 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