CoreData 关系延迟加载?
当我有一个名为“Book”的 CoreData 实体,它与另一个实体(“Bookmark”)具有一对一关系时,我需要插入“Book”的实例和“Bookmark”的实例进入托管对象上下文,并手动分配关系?
如果我执行以下代码来实例化“Book”的实例...
Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:managedObjectContext];
我是否可以执行以下代码来检索其书签而不将“Bookmark”实例插入到相同的托管对象上下文?
book.bookmark;
CoreData 会为我分配一个新的“书签”实例吗?
在你让我尝试一下并亲自看看之前:我已经做到了。我要么做错了什么,要么我打算实例化“Book”和“Bookmark”的两个实例并手动分配关系。在我的测试中,该关系具有“可选”未勾选,但未附加到任何内容。在“book”实例上调用 getter“书签”时,我收到“nil”。
我希望能够使用上面的代码,因为它将允许我的控制器对象处理托管对象上下文,而我的模型对象可以完全忽略它。根据我对 CoreData 的了解,这似乎是预期的实现。如果我错了,请纠正我。
When I have a CoreData entity named, say, 'Book', which has a one-to-one relationship with another entity ('Bookmark') would I need to insert both an instance of 'Book' and an instance of 'Bookmark' into a managed object context, and manually assign the relationship?
If I perform the following code to instantiate an instance of 'Book'...
Book *book = [NSEntityDescription insertNewObjectForEntityForName:@"Book" inManagedObjectContext:managedObjectContext];
Can I, or can I not, perform the following code to retrieve its bookmark without inserting an instance of 'Bookmark' into the same managed object context?
book.bookmark;
Will CoreData allocate a new instance of 'Bookmark' for me?
Before you ask me to try this and see for myself: I have. I'm either doing something wrong, or I'm meant to instantiate both instances of 'Book' and 'Bookmark' and assign the relationship manually. In my testing, the relationship has 'optional' unticked but is not attached to anything. Upon invoking the getter 'bookmark' on a 'book' instance, I receive 'nil'.
I'd like to be able to use my code above, as it will allow my controller objects to deal with the managed object context, while my model objects can ignore it entirely. From what I've read of CoreData, this seems to be the intended implementation. Please correct me if I'm wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果
Book
对象始终需要Bookmark
关系,那么您可以为bookmark
属性编写一个自定义 getter 方法,该方法将插入需要时添加书签
对象。Xcode 将为您生成大部分方法。在数据模型编辑器中按住 Control 键单击
书签
,然后选择将 Objective-C 2.0 实现复制到剪贴板
。然后调整如下:If a
Book
object always requires aBookmark
relationship, then you can write a custom getter method for thebookmark
property that will insert abookmark
object when needed.Xcode will generate most to the method for you. In the data model editor control-click on the
bookmark
and chooseCopy Objective-C 2.0 Implementation to the clipboard
. Then tweak something like this:根据我的经验,您必须首先创建两个实体并自己创建关系。
像这样的东西应该是你所需要的:
In my experience you have to create both entities and create the relationship yourself first.
something like this should be what you need: