MikeTheCoder
MikeTheCoder

Reputation: 963

How can I save an object that's related to another object in core data?

I'm having difficulty with a one to one relationship. At the highest level, I have a one to many relationship. I'll use the typical manager, employee, example to explain what I'm trying to do. And to take it a step further, I'm trying to add a one to one House relationship to the employe.

I have the employees being added no problem with the addEmployeesToManagereObject method that was created for me when I subclassed NSManagedObject. When I select an Employee in my table view, I set the currentEmployee of type Employee - which is declared in my .h.

Now that I have that current employee I would like to save the Houses entities attributes in relation to the current employee.

The part that I'm really struggling with is setting the managedObjectContext and setting and saving the houses attributes in relation to the currentEmployee.

I've tried several things but here's my last attempt:

NOTE: employeeToHouse is a property of type House that was created for me when I subclassed NSManagedObject

House *theHouse = [NSEntityDescription 
                   insertNewObjectForEntityForName:@"House"
                   inManagedObjectContext:self.managedObjectContext];
// This is where I'm lost, trying to set the House
// object through the employeeToHouse relationship
self.currentEmployee.employeeToHouse

How can I access and save the houses attributes to the currentEmployee?

Upvotes: 2

Views: 399

Answers (1)

timthetoolman
timthetoolman

Reputation: 4623

since House is setup as an Entity it can be considered a table within the data store. If that truly is the case, you need to setup a 1 to 1 relationship between Employee and House in your data model.

If you have already done so, then it is as simple as calling. Although I'm not as familiar with one to one relationships with Core Data as I am with to-many. In either case, try one of the following

[self.currentEmployee addHouseObject: theHouse];

or

self.currentEmployee.employeeToHouse=theHouse;

then to the save to the managedObjectContext:

NSError *error=nil;
if (![self.managedObjectContext save:&error]{

    NSLog(@"Core Data Save Error:  %@", error);
}

Also, I'm not sure about your particular situation, but your self.managedObjectContext should already be the same as the one pointed to by self.currentEmployee.managedObjectContext.

Good luck,

Tim

Upvotes: 2

Related Questions