Core data save an object with a relationship to an existing object in the database
I am trying to save a new Object to my context, that will have a foreign key reference (relationship many-to-many) to an object already in the database.
How can I set the relationship of this new 开发者_如何学GoObject to save it to the database?. I tried fetching that object and then setting it in the relationship, but that causes an error when saving the context that comes as null.
I also tried recreating it as a new object, thinking core data would not create a new object but just add the relationship, however it did create the new Object.
How can I save this object?
You have to set the object in the relationship from your new object, the inverse relationship will then be set for you.
So, you need to figure out what is causing the error you are seeing.
In CoreData objects generated from mogenerator, the code to add a single object to a relationship set accesses a mutable set from the object property:
NSMutableSet *result = [self mutableSetValueForKey:@"rounds"];
Then you can add your existing object to that set, and try saving the new object.
Alternatley, CoreData for any ManagedObject generates a method:
- (void)addRoundsObject:(Round*)value_;
If you use that method it should also add the object correctly.
精彩评论