I've been learning how to use Core Data in xcode for a couple of weeks now but have been stumped on how to get the relationships to work.
In my code I have 2 entities. The "House" entity and the "City" entity. A house can only belong in 1 city, but a city can have many houses associated with it. So I set up a one-to-many relationship between the house and city entities.
The following code snippet is in the city view controller, which is just a table view that displays all available cities to choose from. The list is pre-populated in the city entity. Now when I select a row I try to execute the following code to associate a house with the selected city but the result is always nil.
The referringObject is the house object that I am creating cities is the relationship from the house to the city entity
Any help is appreciated
NSManagedObject *selectedCity =
[self.fetchedResultsController objectAtIndexPath:indexPath];
[self.referringObject setValue:[selectedCity valueForKey:@"cityname"]
forKeyPath:@"cities.cityname"];
You want to associate the city object with the house object. You don't need to change the cityname value inside of it. That way you only have one entry in the table for each city. So what you want to do is:
NSManagedObject *selectedCity = [self.fetchedResultsController objectAtIndexPath:indexPath];
[self.referringObject setValue:selectedCity forKeyPath:@"city"];
That'll set up your both relationships for you. You can then access the city's name from a house object with houseObj.city.cityname or get the list of houses in a city with city.houses (assuming you named the relationship houses).