Alpinista
Alpinista

Reputation: 3741

CoreData one-to-many and inverse relationship problem

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

Upvotes: 7

Views: 8042

Answers (1)

Massimo Cafaro
Massimo Cafaro

Reputation: 25429

There are different possibilities. If you already have a Category object (for instance obtained through a fetch request), and assuming the variables

Category *category;
Item *item;

then you simply do the following:

item.category = category;

or

[category setValue: category forKey:@"category"];

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:

// Create a new instance of the entity 
Category *category = (Category *) [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:managedObjectContext];
// add all of the category properties, then set the relationship
// for instance set the category name
[category setValue:@"myCategoryName" forKey:@"name"];
[category setValue:item forKey:@"item"];

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:

[category addItemObject:item];

or the inverse:

[item addCategoryObject:category];

Upvotes: 9

Related Questions