0

我有以下简单的关系:

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。

我在任何地方都使用相同的上下文。

我想我的引用做错了什么,但我不确定它是什么?

4

1 回答 1

0

回应您的最后评论:

我相信当孩子 ID 从临时更新为永久时会发生这种情况。不知何故,Core Data 做了一些破坏参考的事情。

你几乎肯定是正确的。这是文档中关于objectId

重要提示:如果接收者尚未保存,则对象 ID 是一个临时值,将在保存对象时更改。

话虽这么说,如果您对孩子有一些其他独特的属性,您可以使用 KVO 进行比较:

int idx = [[children valueForKey:@"uniqueProperty"] indexOfObject:_child.uniqueProperty];
于 2013-11-05T15:22:44.347 回答