导入核心数据时建立关系?

Mat*_*hew 6 import cocoa persistence core-data

我有一个名为importMoc的内存管理对象上下文,用于导入记录(例如员工).我已经解析了一个文件并在importMoc中设置了雇员对象,但有一个非常重要的例外.用户确认他们想要处理%d名员工但我无法弄清楚如何或何时设置员工的"父母"关系(例如设置他们的部门).

为了我的目的,他们将全部导入到同一部门(用户已经隐式选择).

显然我不能在两个上下文中建立关系,所以我:

  1. 在importMoc中创建一个部门,然后当我合并更改时,将"导入"部门与"真实"部门合并?
  2. 2)合并员工,然后获取所有刚刚进口的员工(不知何故!!!)然后设置他们的部门?
  3. 3)我忽略了一些其他解决方案?

这似乎是一个简单的问题,但出于某种原因(懒惰?疲倦?愚蠢?)我无法弄清楚如何去做!到目前为止,我所尝试的一切似乎都过于复杂和复杂!

提前致谢!

dic*_*ciu 0

1/ 假设员工记录 X 的姓名为 Y,部门 ID 为 15(即,它通过关系引用 ID 为 15 的部门)

2/ 从托管对象上下文中加载部门 ID 为 15 的部门

3/ 创建一个引用在 (2) 创建的对象的员工

即(注意:仅示例代码,可能无法编译):

NSEntityDescription * departmentED = [NSEntityDescription entityForName:@"Department" inManagedObjectContext:moc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(id == %@)", deptId];

NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:departmentED];
[request setPredicate:predicate];

NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];

/* create employee */

NSEntityDescription * employeeED = [NSEntityDescription entityForName:@"Employee" inManagedObjectContext:moc];
NSManagedObject * employeeMO = [[[NSManagedObject alloc] initWithEntity:employeeED insertIntoManagedObjectContext:moc] autorelease];

/* set employee department to department instance loaded above */
[receiptObject setValue:[array objectAtIndex:0] forKey:@"department"];
Run Code Online (Sandbox Code Playgroud)