CoreData - one-to-many modeled relationship comes out as one-to-one

ε祈祈猫儿з 提交于 2019-11-27 02:42:17

问题


I am new to Core Data modeling, and I am having a hard time understanding how one-to-many relationships work.

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.

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).

What would be the correct way to tell the Core Data Model that this relationship allows many comments in one Task?

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?

Thanks for any suggestions!


回答1:


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

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.

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.

If you want to retrieve all comments for a given task you need to iterate the NSSet(comments) property of that task.



来源:https://stackoverflow.com/questions/8280777/coredata-one-to-many-modeled-relationship-comes-out-as-one-to-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!