2013-07-21 42 views
0

我試圖從核心數據中調用與特定類別關聯的所有內容。該應用程序是這樣的:基於實體關係的核心數據提取

  • 單擊類別
  • 點擊一個子類的問題
  • 查看的問題

我都設置了意見,並已設置夥伴核心數據,但我遇到了這個問題,無論我選擇哪個類別,它仍然會加載所有問題。

我從類別列表視圖中傳遞類別選擇,但我不知道如何處理它,以及我應該如何從核心數據調用。我目前有這個(同樣,它返回所有問題):NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:[appDelegate managedObjectContext]];

這些類別和問題在數據模型中有反比關係。我應該使用謂詞,NSRelationshipDescription還是其他?

+1

你的數據模型是什麼樣的?是否有一個單獨的管理對象的類別,子類別和問題? – bbarnhart

+0

@bbarnhart是的,分開的對象,與兩者之間的關係。 –

回答

0

你不能只訪問NSSet的問題嗎?即category.questions

要獲得關於謂語問題:

如果你想找到所有Questions特定Category你需要指定CategoryNSPredicate

喜歡的東西:

(NSArray *)findQuestionsForCategory:(Category *)category { 
NSFetchRequest *fetch = [[NSFetchRequest alloc] init]; 
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:[appDelegate managedObjectContext]]; 
[fetch setPredicate:[NSPredicate predicateWithFormat:@"question.category == %@", category]]; 

... execute fetch request, handle possible errors ... 

} 
0

使用NSPredicate(假設您使用的是傳統的Master-Detail UITableView模式和Storyboard) :

// In CategoryViewController 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender 
{ 
    if ([[segue identifier] isEqualToString:@"categorySelect"]) 
    { 
     Category *category; 
     category = [categories objectAtIndex:[self.tableView indexPathForSelectedRow].row]; 
     [segue.destinationViewController setParentCategory:category]; 
    } 
} 

// In QuestionViewController with @property parentCategory 
- (void)viewDidLoad 
{ 
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; 
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:managedObjectContext]; 
    [fetchRequest setEntity:entity]; 

    // Create predicate 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(category == %@)", self.ParentCategory]; 
    [fetchRequest setPredicate:predicate]; 

    NSError *error; 
    questions = [managedObjectContext executeFetchRequest:fetchRequest error:&error]; 
} 
相關問題