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];
Massimo cafafo
source share