基于实体关系的核心数据获取

时间:2013-07-21 22:42:56

标签: ios objective-c core-data

我正在尝试从Core Data调用与特定类别相关的所有内容。该应用程序是这样的:

  • 点击类别
  • 点击子类别问题
  • 查看问题

我已经设置了所有视图,并且有一个合作伙伴设置了Core Data,但是遇到了这个问题,无论我选择哪个类别,它仍然会加载所有问题。

我从类别列表视图中传递了类别选择,但我不知道如何处理它,以及我应该如何从Core Data调用。我现在有这个(再次,它返回所有问题):NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:[appDelegate managedObjectContext]];

类别和问题在数据模型中具有反比关系。我应该使用谓词,NSRelationshipDescription还是其他什么?

2 个答案:

答案 0 :(得分:0)

你能不能只访问NSSet个问题?即category.questions

回答有关谓词的问题:

如果您希望查找特定Questions的所有Category,则需要在Category

中指定NSPredicate

类似的东西:

(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 ...

}

答案 1 :(得分: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];
}