I am trying to create a new Core Data entity and copy [some of] its contents from an old entity, using the following (simplified) code:
NSManagedObjectContext *context = [[UIApplication sharedApplication] delegate]).managedObjectContext;
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"MyEntity" inManagedObjectContext:context];
MyEntity *newEntity = [[MyEntity alloc] initWithEntity:entityDescription insertIntoManagedObjectContext:context];
newEntity.myRelationship = oldEntity.myRelationship;
Before the last assignment is executed, oldEntity has an object pointed by myRelationship.
After the assignment, newEntity.myRelationship points to the same object, but oldEntity.myRelationship becomes nil.
What do I have to do to keep the object in the old entity as well as in the new entity?
Your relationship is of type
X.oldEntityandnewEntityboth have aone-to-onerelation ship toX.I think your relationship from
Xto the old and new entity type is alsoone-to-one.You should change this.
In your core data model you can change this.
It should look like:
Type X <-->> Type YWhere type
Yis the type for your old and new entity.You should regenerate your
NSManagedObjectclass for TypeX. If you have logic in the implementation, you should copy and paste it in the new generated file.Note that entity X has now more then 1 entity of type Y, so it will be a collection instead of a single entity.