2013-07-21 108 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]; 
} 
相关问题