iPhone core data inserting new objects

core-data, insert, iphone

Solution

When you define the relationship in the data model the set is defined in the header of the containing object. Just add or remove items from the set using the normal NSMutableSet methods.

To add a new managed entity you will do something like:

Task* newTask = [NSEntityDescription insertNewObjectForEntityForName:@"Task" inManagedObjectContext:self.managedObjectContext];

If you grab the Location sample from Apple and work from there you will puzzle it out although that contains no relationships. To get it all working just change your data model to what it needs to be and don't think of it as a relationship, just think of it as "A has a NSMutableSet of B". Because you defined the reverse relationship as the documentation recommended you don't need to think about what B has of A, just start thinking in terms of B when that's the object that matters to you.

Let's say you have an Airport object which has a Board object (and imagining you set origin and destination into Flight with a variable `routingArray`, then just create your Flight objects as necessary and set the relationship like:

Flight* newFlight = [NSEntityDescription insertNewObjectForEntityForName:@"Flight" inManagedObjectContext:self.managedObjectContext];
[newFlight setRoute:routingArray];
[Airport.Board.flights addObject:newFlight];

When the flight is cancelled (curse you, United!) you can just remove the Flight from that set and anyone who tries to access the object where it used to be see nil, so you can cheerfully ruin the passengers day.

Problem

I have been reading through the core data documentation and feel I am still missing something. I do not quite understand how you insert objects into a relationship of another object. For example the following two Entities are in my model ``` flightDepartureBoard name: from_airport: to_airport: current_flights: (this is a one to many relationship of flight detail entities) flight_details arrive depart name ``` So my data contains a list of different departure boards for a few airports. Each departure board then contains a number of flight_details containing info on the current arrivals and departures for that airport. My current understanding is to insert the flight details for a specific departure board, I must get the managedObject for the board, then create a new managed object for each flight and set its values as appropriate then create an NSSet conatining the flight managed objects and set the depatureboards managedObject current_flights (the relationship) to the just created NSSet. Is this correct? What if I want to add new entries? I assume I do not need to fetch the entire set first? Thanks for any help.. Although I just realised I could set the relationship to the current object on the flightDetails object instead..

Original source