【问题标题】:Core Data Fetch Based on Entity Relationship基于实体关系的核心数据获取
【发布时间】:2013-07-21 22:42:56
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 你的数据模型是什么样的?类别、子类别和问题是否有单独的托管对象?
  • @bbarnhart 是的,单独的对象,两者之间有关系。

标签: ios objective-c core-data


【解决方案1】:

您不能只访问NSSet 的问题吗?即category.questions

回答关于谓词的问题:

如果您要查找特定Category 的所有Questions,则需要在NSPredicate 中指定Category

类似:

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

}

【讨论】:

    【解决方案2】:

    使用 NSPredicate(假设您使用的是传统的 Master-Detail UITableView 模式和情节提要):

    // 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];
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2013-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-25
      相关资源
      最近更新 更多