我正在尝试修改联系人的简单核心数据获取请求,以仅查找与某个标签有关系的联系人。Contact 和 Tag 都是具有多对多关系的实体。
我了解 Core Data 我可以通过首先获取Tag对象,然后调用tag.contact来做到这一点,但我不想这样做,因为其余代码取决于 fetchResultsController 返回Contact的事实对象,而不是标签对象。
如果我要做关系数据库,我可以做一个简单的跨表查询并找到所有带有特定标签的联系人。有没有一种简单的方法可以通过 Core Data 复制它?
-(NSFetchedResultsController *) fetchedResultsController {
//if fetch controller already exists
if(_fetchedResultsController != nil) {
return _fetchedResultsController;
}
//create a new fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact"
inManagedObjectContext:[self managedObjectContext]];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lastName"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
//instantiate the fetch controller with the fetch request and sort by last name into sections
_fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:[self managedObjectContext] sectionNameKeyPath:nil cacheName:nil];
//declare delegate of fetch controller as self
_fetchedResultsController.delegate = self;
NSLog(@"fetchResultsController Created");
return _fetchedResultsController;
}