我有一个与此类似的Core Data模型:
-
公司实体
-
companyName属性(字符串)
-
与员工实体的To-Many关系 .
-
员工实体
-
employeeID属性(字符串)
-
与父公司实体的To-One关系
我有一个根视图控制器,它在表视图中列出了公司 . 然后选择一行将所选公司的索引推送到另一个视图控制器,该控制器在表中列出Employee .
- (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];
}
在Employee视图控制器中,公司设置为NSManagedObject .
- (void)setCompany:(NSManagedObject *)co
{
[co retain];
[company release];
company = co;
[self setTitle:[company valueForKey:@"companyName"]];
}
我添加新员工的代码如下所示:
employee = [NSEntityDescription insertNewObjectForEntityForName:@"Employee" inManagedObjectContext:moc];
[[company mutableSetValueForKey:@"employee"] addObject:employee];
[employee setValue:employeeID forKey:@"employeeID"];
这看起来正确地插入数据库,我可以看到插入到Employee表中的公司的外键ID .
我正在尝试取一家公司的所有员工,但我遇到了困难 .
这是我对NSFetchRequest的所有内容,但它只是给了我所有的员工(不是公司):
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];
1 回答
如果为实体生成类,则可以简单地处理此问题 . 在XCode中编辑模型时,单击Cmd-N以创建新文件 . 选择左侧的iOS Cocoa Touch Class,然后选择右侧的Managed Object Class . 点击Next,Next,Next,将为您生成代表您的实体的类文件 .
这些类是金色的,因为它们将帮助您管理对象之间的所有连接 . 在您的模型中,如果您定义从公司到员工的多对多关系并将其称为员工,那么您的公司类将具有employees属性,该属性是与该特定公司关联的所有员工的NSSet . 这是梦幻般的 .
您的创建代码看起来更像这样:
然后,为了获得与贵公司关联的员工列表,它就像这样简单: