Tuesday, 1 October 2013

iOS Core Data: How do I add subsequent records to the 'many' of 1:many relationships?

iOS Core Data: How do I add subsequent records to the 'many' of 1:many
relationships?

I am writing an GPS running app that I want to store multiple locations
per 'Path' or run. I am having a little trouble understanding the new
concepts of ORM style DBs. (I know Core Data uses SQLLite as the
underlying mechanism and isn't a true ORM, but that aside..,) I have two
entities setup, 'Path' and 'Location', with a 'To-Many' relationship going
from Path>>Location with Cascade Deletion, and an inverse that just has
nullify for Delete.

I am doing:
//SEND TO CORE DATA
bdAppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
// get GPS lat/lng
double lat = newLocation.coordinate.latitude;
double lng = newLocation.coordinate.longitude;
// insert Path
Path *currentPathInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Path"
inManagedObjectContext:context];
currentPathInfo.name = currentPathName;
currentPathInfo.createddate =[NSDate date];
// insert location/GPS point
Location *currentPathLocation = [NSEntityDescription
insertNewObjectForEntityForName:@"Location"
inManagedObjectContext:context];
currentPathLocation.lat = [NSNumber numberWithDouble:lat];
currentPathLocation.lng = [NSNumber numberWithDouble:lng];
// insert 'Location' relationship to 'Path'
[currentPathInfo addLocationsObject:currentPathLocation];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error
localizedDescription]);
}
This is on initial startup (button press) but then how do I continue to
add more 'Locations' that relate to the initial 'Path' without continuing
to add more 'Path's as a result of repeating the above code?
In SQL, I'd have a PathID integer (identity) that I'd use for a foreign
key in a 'Locations' table to insert locations... I'm having a
disconnect...

No comments:

Post a Comment