I am trying to import a set of data into a CoreData persistentStore. This is read-only data that will be presented to the user at run-time.
I have an entity called “Category” that has a one-to-many relationship with an entity called “Item”, which in turn has an inverse relationship to a Category.
As I add Items to the context, how do I associate them with the correct Category? I can see in the SQLite dB that it is done by adding a Category field to the Item table, and probably uses the Categories primary key for the relationship. But the PK is behind-the-scenes… is there a method for making the connection?
I also see in my Category class that there are methods generated by CoreData for adding Items, but I am assuming that these are alos behind-the-scene methods that allow CoreData to maintain the relationships:
@interface Category (CoreDataGeneratedAccessors)
- (void)addItemObject:(Item *)value;
- (void)removeItemObject:(Item *)value;
- (void)addItems:(NSSet *)value;
- (void)removeItems:(NSSet *)value;
@end
I read in the programing guide that CoreData takes care of the other side of the relationship automatically, but I can’t figure out how do do the initial link to a Category as I add Items.
Thanks
jk
There are different possibilities. If you already have a Category object (for instance obtained through a fetch request), and assuming the variables
then you simply do the following:
or
and you are done, since Core Data automatically sets the inverse relationships.
If you do not have a Category object, or you want to insert a new one, do the following:
Then you set this Category object for your Item object exactly as before.
Finally, the methods you have shown are not used behind the scenes by Core Data: these methods are available to you, so that you can also do the following:
or the inverse: