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