[英]Core Data: confused with relationships
我有以下简单关系:
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。
我到处都使用相同的上下文。
我想我的参考文献做错了什么,但是我不确定这是什么吗?
针对您的最后评论:
我相信,当孩子ID从临时更新为永久时会发生这种情况。 核心数据以某种方式破坏了参考。
您几乎可以肯定是正确的。 这是有关objectId
的文档的内容:
要点:如果尚未保存接收器,则对象ID是一个临时值,在保存对象时会更改。
话虽如此,如果您的孩子有其他独特的属性,则可以使用KVO进行比较:
int idx = [[children valueForKey:@"uniqueProperty"] indexOfObject:_child.uniqueProperty];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.