I have the following datamodel:
entityA<-->>entityB<<-->>entityC
entityD<-->>entityE
Note that entityD and entityE do not have relationship with A-C.
My DetailViewController takes in properties from managed objects and saves as a new managed object to the managedObjectContext.
I currently display the existing managed object in UILabels like this:
UILabel1.text = [self.selectedEntityB nameB];
UILabel2.text = [self.selectedEntityA nameA];
I then save to the context in the save action here:
- (IBAction)save:(id)sender {
EntityD *newEntityD = [NSEntityDescription insertNewObjectForEntityForName:@"EntityD"
inManagedObjectContext:self.managedObjectContext];
[newEntityD setValue:self.UILabel2.text forKey:@"nameD"];
EntityE *newEntityE = [NSEntityDescription insertNewObjectForEntityForName:@"EntityE"
inManagedObjectContext:self.managedObjectContext];
[newEntityE setValue:self.UILabel1.text forKey:@"nameE"];
NSError *anyError = nil;
BOOL savedSuccessfully = [self.managedObjectContext save:&anyError];
if (!savedSuccessfully) {
}
}
This works for setting nameD and nameE. I'm trying create a relationship between the newly created objects for EntityD and EntityE. Lets say relationship from entityE to entityD is toD. I've tried in the save action:
[newEntityE setValue:self.UILabel2.text forKey:@"toD"];
But I get error with: 'NSInvalidArgumentException', reason: '-[__NSCFString managedObjectContext]: unrecognized selector sent to instance 0x10939fd00'
How would I establish relationship between the newly created objects?
The relationship is implicitly created when you assign EntityD to EntityE via the relationship 'property'. Take a look at the header files for each of these entities. You should have a property in EntityE like this (given the to-one relationship from E to D):
@property (nonatomic, retain) EntityD *toD;
This means that you have to assign an EntityD 'object' to newEntityE through it's relationship property toD as follows:
// assuming EntityD has some property like NSString *name then
newEntityD.name = self.UILabel2.text;
newEntityE.toD = newEntityD;
It looks like you are trying to assign an NSString directly instead of updating the name property of newEntityD and then assigning the newEntityD object to newEntityE through the relationship.