CoreData One-to-Many and Feedback

I am trying to import a dataset into a CoreData persistentStore repository. This is read-only data that will be presented to the user at runtime.

I have an object called Category, which has a one-to-many relationship with the Item object, which in turn has feedback with the category.

How do I add items to the context, how do I associate them with a suitable category? I see in SQLite dB that this is done by adding the Category field to the Item table and probably uses the Category primary key for the relationship. But the PC is behind the scenes ... is there a way to make a connection?

I also see in my Category class that there are methods generated by CoreData to add elements, but I assume that these are alos-behind-the-scenes methods that allow CoreData to maintain 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 programming guide that CoreData automatically takes care of the other side of the relationship, but I cannot figure out how to make the original Category link when adding elements.

thanks

Jk

+7
iphone core-data
source share
1 answer

There are various possibilities. If you already have a Category object (for example, obtained using a select query) and assuming variables

 Category *category; Item *item; 

then you just do the following:

 item.category = category; 

or

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

and you're done, since Core Data automatically sets up the reverse relationship.

If you do not have a Category object or want to insert a new one, follow these steps:

 // 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 the Item object in exactly the same way as before. Finally, the methods you showed are not used behind the scenes of Core Data: these methods are available to you, so you can also do the following:

 [category addItemObject:item]; 

or vice versa:

 [item addCategoryObject:category]; 
+9
source share

All Articles