CoreData - 一对多的建模关系是一对一的 [英] CoreData - one-to-many modeled relationship comes out as one-to-one
问题描述
我是 Core Data 建模的新手,我很难理解一对多关系的工作原理.
I am new to Core Data modeling, and I am having a hard time understanding how one-to-many relationships work.
我有一个名为 Task
的父实体,它可以有多个 Comment
实体的实例.我这样建模:在Comments
上,与Task
的关系称为task
,Task
实体是一个目的地.在Task
上,有一个叫做comments
的关系,以Comment
为目的地,两个关系互为逆.
I have a parent entity called Task
, which can have several instances of Comment
entity. I modeled it like this: on Comments
, a relationship to Task
called task
with the Task
entity a destination. On Task
, a relationship called comments
, with Comment
as its destination, and both relationships are each others inverse.
不定义反向会导致警告或错误消息.在以这种方式建模时,我注意到一旦我为给定的 Task
创建了第二条评论,第一个评论就会被替换(一对一关系).
Not defining an inverse results in either warnings or error messages. While modeling this way works, I've noticed that once I create a second comment for a given Task
, the first is replaced (one-to-one relationship).
告诉核心数据模型这种关系允许在一个Task
中有很多评论的正确方法是什么?
What would be the correct way to tell the Core Data Model that this relationship allows many comments in one Task
?
此外,由于 CoreData 似乎自己管理主键,我将如何创建 NSPredicate
来检索给定任务的所有评论?
Also, since CoreData seems to manage primary keys on its own, how would I create an NSPredicate
to retrieve all comments for a given Task?
感谢您的任何建议!
推荐答案
首先你需要在Task
实体中设置plural
选项,在你的.xdatamodeled
并选择Task
实体的relationship
属性到comments
你应该可以看到这个
First of all you need to set the plural
option in the Task
entity, select it in your .xdatamodeled
and select the relationship
property of Task
entity to comments
you should be able to see this
有一个 plural
选项,请务必检查一下.您必须重新创建 NSManagedObject
如果您使用生成的类,并且如果您使用 sqlite 存储,您必须删除和重建,这样它就不会抱怨新架构与旧架构不同.
there is a plural
option be sure to check that out. You must recreate your NSManagedObject
if your using generated classes and also if your using sqlite store you must delete and rebuild so it will not complain about the new schema not being the same with the old one.
要检查您是否有一对多关系,您的 Task
实体应该有一个名为 comments 的属性,它是 NSSet
的类类型,而不是 Comments.
To check if you have a one to many relationship your Task
entity should have a property called comments which is a class type of NSSet
not Comments.
如果您想检索给定任务的所有评论,您需要迭代该任务的 NSSet(comments)
属性.
If you want to retrieve all comments for a given task you need to iterate the NSSet(comments)
property of that task.
这篇关于CoreData - 一对多的建模关系是一对一的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!