How to create an NSFetchRequest which filters Core Data objects based on parent relationships?
I have a Core Data model similar to this:
- Company Entity
- companyName attribute (string)
- To-Many relationship to Employee entities.
- Employee Entity
- employeeID attribute (string)
- To-One relationship to a parent Company entity
I have a root view controller which lists the Company's in a table view. Then selecting a row pushes the index of the selected Company to another view controller which lists Employee's in a table.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)ip
{
EmployeeListViewController *anotherViewController = [[EmployeeListViewController alloc] init];
[anotherViewController setCompany:[companyList objectAtIndex:[ip row]]];
[[self navigationController] pushViewController:anotherViewController animated:YES];
[anotherViewController release];
}
In the Employee view controller, the company is set to a NSManagedObject.
- (void)setCompany:(NSManagedObject *)co
{
[co retain];
[company release];
company = co;
[self setTitle:[company valueForKey:@"companyName"]];
}
My code to add a new Employee looks like this:
employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:moc];
[[company mutableSetValueForKey:@"employee"] addObject:employee];
[employee setValue:employeeID forKey:@"employeeID"];
This looks to be inserting the database correctly and I can see the foreign key ID of the Company inserted into the Employee table.
I'm trying to fetch all the Employee's in a company but I'm getting stuck.
Here's what I have for the NSFetchRequest but it just gives me all the Employee's (not by company):
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
[fetch setEntity:[NSEntityDescription entityForName:@"Employee" inManagedObjectContext:moc]];
[fetch setEntity:entity];
NSError *error = nil;
NSArray *results = [moc executeFetchRequest:fetch error:&error];
[fetch release];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
This can be handled simply if you generate classes for your entities. When you are editing the model in XCode, hit Cmd-N to create a new file. Choose iOS Cocoa Touch Class on the left and choose Managed Object Class on the right. Hit Next, Next, Next and class files that represent your entities will be generated for you.
Those classes are golden because they will help you manage all of your connections between objects. In your Model if you define a to-many relationship from Company to Employee and call it employees, then your Company class will have an employees property which is an NSSet of all of the Employees associated with that particular company. It's fantastic.
Your creation code would look more like this:
Then to get the list of employees associated with your company, it is as simple as this: