![](/img/trans.png)
[英]Trying to fetch results in Core Data based on Entity's relationship object in iOS
[英]Core Data Fetch Based on Entity Relationship
我正在尝试从Core Data中调用与特定类别相关联的所有内容。 该应用程序是这样的:
我已经设置了所有视图,并让一个合作伙伴设置了Core Data,但是遇到一个问题,无论我选择哪个类别,它始终会加载所有问题。
我从类别列表视图传递了类别选择,但是我不确定该如何处理以及如何从Core Data调用。 我目前有这个(再次返回所有问题): NSEntityDescription *entity = [NSEntityDescription entityForName:@"Question" inManagedObjectContext:[appDelegate managedObjectContext]];
类别和问题在数据模型中具有相反的关系。 我应该使用谓词,NSRelationshipDescription还是其他方式?
您不仅可以访问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 ...
}
使用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];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.