正如在 cmets 中已经提到的,Core Data 关系描述了一个对象与一组不同其他对象的关系。一个对象不可能与同一个对象有多个关系。
我想到的一个可能解决方案是在WorkingPlan 和Position 之间引入另一个实体WorkingStep:
-
steps 是从WorkingPlan 到WorkingStep 的有序 对多关系,
-
plan 是一对一的反比关系,
-
position 是从 WorkingStep 到 Position 的一对一关系,
-
steps 是一对多的反比关系。
我建议了一个从WorkingPlan 到WorkingStep 的有序关系,因为我假设一个计划的步骤必须按照定义的顺序执行。
例如,如果必须按顺序为计划执行位置“pos1”、“pos2”、“pos1”,您将在计划中添加 3 个步骤“step1”、“step2”、“step3” ,并且“step1”和“step3”都与“pos1”相关,“step2”与“pos2”相关。
向有序关系添加值有点棘手。以下代码展示了如何创建上述对象:
WorkingPlan *plan1 = [NSEntityDescription insertNewObjectForEntityForName:@"WorkingPlan" inManagedObjectContext:context];
WorkingStep *step1 = [NSEntityDescription insertNewObjectForEntityForName:@"WorkingStep" inManagedObjectContext:context];
WorkingStep *step2 = [NSEntityDescription insertNewObjectForEntityForName:@"WorkingStep" inManagedObjectContext:context];
WorkingStep *step3 = [NSEntityDescription insertNewObjectForEntityForName:@"WorkingStep" inManagedObjectContext:context];
Position *pos1 = [NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:context];
Position *pos2 = [NSEntityDescription insertNewObjectForEntityForName:@"Position" inManagedObjectContext:context];
step1.position = pos1;
step2.position = pos2;
step3.position = pos1;
// temporary proxy object used to modify the ordered to-many relationship "steps":
NSMutableOrderedSet *tmpMutableSteps = [plan1 mutableOrderedSetValueForKey:@"steps"];
[tmpMutableSteps addObject:step1];
[tmpMutableSteps addObject:step2];
[tmpMutableSteps addObject:step3];
更多信息:
您也可以像这样在一个“步骤”中设置plan1.steps:
plan1.steps = [NSOrderedSet orderedSetWithObjects:step1, step2, step3, nil]; // works!
但某些访问器方法不适用于有序关系:
[plan1 addStepsObject:step1]; // does not work!
似乎是“合乎逻辑的步骤”,但它抛出了NSInvalidArgumentException:
*** -[NSSet intersectsSet:]: set argument is not an NSSet
这似乎是自动生成的访问器方法中的一个错误,其他人已经注意到了(例如Exception thrown in NSOrderedSet generated accessors)。使用代理对象是解决该问题的一种解决方法。