如何使用Core Data从不相关的实体获取数据?

时间:2014-07-02 06:36:48

标签: ios objective-c core-data nspredicate nsfetchrequest

enter image description here

我有这三个不相关的实体。我怎样才能获得员工的工资。我想要这样的东西:

Select C.salary FROM Employee A, Department B, Salaries C Where A.id=B.empid AND B.id=C.deptid AND A.id=12

我需要在核心数据中执行相同的上述操作。

1 个答案:

答案 0 :(得分:0)

正如马丁所说,简单的方法是建立所需的关系并遍历它们。

但是如果您没有权限来更改模型,则需要在检索后对您拥有的内存对象进行管理。换句话说,您需要使用正确的NSFetchRequest s设置NSPredicate

例如,检索给定员工的部门。

NSFetchRequest * request = [NSFetchRequest fetchRequestWithEntityName:@"Department"]; 
request.predicate = [NSPredicate predicateWithFormat:@"empid", @(12)];

NSError *error = nil;
NSArray *departments = [moc executeFetchRequest:request error:&error];
if(departments) {
    // do a NSLog for departments here to see what you have
    // here you can access deptid for each department you retrieve
    // and with that value run another request against Salaries
    // e.g. NSManagedObject* department = [departments lastObject];
    //      NSNumber* deptid = [department valueForKey:@"deptid"]   
} else {
    // handle error here

}

其他部分留作excersise;)