I am importing data from a web service, in such data I have a tree of categories.
For example:
Restaurants
– Italian
– Mexican
– Steakhouse
In my model I have set a relation called ParentCategory with an inverse relation called Subcategories. Everything is good so far.
Now, when I am importing my categories I am doing something like this: (Note: My code does not look like this. I have changed it to exemplify my problem)
NSEntityDescription *categoryEntity = [NSEntityDescription entityForName:@"Categories" inManagedObjectContext:context];
NSDescription *parentCategory = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context]
//Then I actually set some values for parentCategory.
//Then create the subcategories.
NSDescription *italianDescription = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context];
[italianDescription objectForKey:@"Italian" forKey:@"name"];
//Set the relationship
[italianDescription objectForKey:parentCategory forKey:@"ParentCategory"];
//All this works great but then when
NSEntityDescription *mexicanDescription = [NSEntityDescription insertNewObjectForEntityForName:[categoryEntity name] inManagedObjectContext:context];
[mexicanDescription objectForKey:@"Mexican" forKey:@"name"];
[mexicanDescription objectForKey:parentCategory forKey:@"ParentCategory"];
It seems like when that last line of code runs it removes the relation from “italianDescription”, therefore after I save my context it shows like it doesn’t have a parent category. I removed some data from my web service and only the last subcategory that I set the relation to parent category object X keeps it. All previous will loose it.
I checked the apple developer documentation and it doesn’t really help. That being said, how can I overcome this? Or what would be a efficient way to import that with relations.
I don’t think you are setting anything, the way to set values for NSManagedObjects is
Instead of NSDescription*’s you should be using NSManagedObject*
You may want to look into subclassing your entities as it allows for much easier access and setting of properties. In which case it would be
Then you can set the values just by using it’s properties with dot notation or messaging. You can do this by selecting the entity in the core-data editor and then under Editor on the Menu bar there is an option to create a NSManagedObject subclass, after you create that you need to tell the entity that it has a custom class now. This is done in the right hand Utiliies bar under Entity there is a Class field, just enter the name of your new class and it should be set up.