核心数据保存一个对象与数据库中现有对象的关系
我正在尝试将一个新对象保存到我的上下文中,该对象将具有对数据库中已有对象的外键引用(多对多关系)。
如何设置这个新对象的关系以将其保存到数据库中?我尝试获取该对象,然后将其设置在关系中,但这会在保存为空的上下文时导致错误。
我还尝试将其重新创建为新对象,认为核心数据不会创建新对象而只是添加关系,但它确实创建了新对象。
我怎样才能保存这个对象?
I am trying to save a new Object to my context, that will have a foreign key reference (relationship many-to-many) to an object already in the database.
How can I set the relationship of this new Object to save it to the database?. I tried fetching that object and then setting it in the relationship, but that causes an error when saving the context that comes as null.
I also tried recreating it as a new object, thinking core data would not create a new object but just add the relationship, however it did create the new Object.
How can I save this object?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须在新对象的关系中设置对象,然后将为您设置逆关系。
因此,您需要找出导致您看到的错误的原因。
在 mogenerator 生成的 CoreData 对象中,将单个对象添加到关系集的代码从对象属性访问可变集:
然后,您可以将现有对象添加到该集,并尝试保存新对象。
或者,任何 ManagedObject 的 CoreData 都会生成一个方法:
如果您使用该方法,它也应该正确添加对象。
You have to set the object in the relationship from your new object, the inverse relationship will then be set for you.
So, you need to figure out what is causing the error you are seeing.
In CoreData objects generated from mogenerator, the code to add a single object to a relationship set accesses a mutable set from the object property:
Then you can add your existing object to that set, and try saving the new object.
Alternatley, CoreData for any ManagedObject generates a method:
If you use that method it should also add the object correctly.