核心数据:与关系混淆

时间:2013-11-05 13:53:46

标签: ios core-data

我有以下简单的关系:

Parent has many Children (ordered)
Child belongs to Parent.

我得到了一个奇怪的行为:

// In of my classes, I keep a reference to a child.
@interface Foo ()
{
    Child *_child;
}

// Somewhere in my code I create a child and a parent and associate them.
Child *c = (Child *)[NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:moc];
Parent *p = (Parent *)[NSEntityDescription insertNewObjectForEntityForName:@"Parent" inManagedObjectContext:moc];
[p addChildrenObject:c];
c.parent = p;
_child = c;

// Then somewhere else I do:
Parent *parent = _child.parent; // It works fine
NSOrderedSet *children = parent.children; // Same, I do see the children
int idx = [children indexOfObject:_child]; // idx is NSNotFound!!

我可以看到children包含具有正常ID的子项,而我的_child引用仍然具有临时ID。

我到处都使用相同的上下文。

我想我的参考文献有问题,但我不确定它是什么?

1 个答案:

答案 0 :(得分:0)

回应你的上一次评论:

  

我相信当子ID从临时更新到时会发生   常驻。不知何故,核心数据做了一些打破参考的东西。

你几乎肯定是对的。以下是documentation关于objectId

的努力
  

重要提示:如果尚未保存接收方,则对象ID为a   保存对象时将更改的临时值。

话虽如此,如果您对孩子有其他独特属性,您可以使用KVO进行比较:

int idx = [[children valueForKey:@"uniqueProperty"] indexOfObject:_child.uniqueProperty];
相关问题