I've once again read through the Apple developer Core Data documentation and found it lacking when it comes to the graphical Xcode 4 editor when creating SQLLite entities much as I found it lacking when IB was separate in Xcode 3.
Three tables:
- ZipData
- LocationData
- CrossReference
CrossReference has the primary key of ZipData and LocationData so I only need to query CrossReference to get all zips for locations or all locations for zips. This means of course a to-many relationship on both ZipData and LocationData (and perhaps on CrossReference?).
What I have (that isn't working) relationship-wise is this :
- ZipData has a relationship "locations" that points to LocationData and is inverse
- LocationData has a relationship "zipsCodes" that points to ZipData and is inverse
- CrossReference table has two relationships, one to ZipData (and is inverse) and one to LocationData (and is inverse).
I'm not sub-classing any of the entities as NSManagedObjects just yet. I am simply doing the code below in the viewDidLoad method, just to see if what I have setup works.
// test/learn the core data frame work
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *locationData = [NSEntityDescription
insertNewObjectForEntityForName:@"LocationData"
inManagedObjectContext:context];
[locationData setValue:@"Testville" forKey:@"City"];
[locationData setValue:@"United Tests" forKey:@"Country"];
[locationData setValue:@"County of Test" forKey:@"County"];
NSManagedObject *zipCodeData = [NSEntityDescription
insertNewObjectForEntityForName:@"ZipCodeData"
inManagedObjectContext:context];
[zipCodeData setValue:[NSNumber numberWithDouble:1111.00] forKey:@"Income"];
[zipCodeData setValue:[NSNumber numberWithDouble:22.00] forKey:@"LandArea"];
[zipCodeData setValue:@"23060" forKey:@"ZipCode"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"CrossReference" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"LocationId: %@", [info valueForKey:@"LocationDataId"]);
NSManagedObject *details = [info valueForKey:@"details"];
NSLog(@"ZipId: %@", [details valueForKey:@"ZipCodeDataId"]);
}
[fetchRequest release];
I don't understand how to setup these relationships and not sure how to trust that somehow the primary keys are setup and the entities just kind of find their way together.
I'm getting nothing back in the logs even though when I view the simulators sqllite db I see the test entities have been persisted (but nothing in CrossReference). I know I'm missing something relationship wise but I can't put my finger on it.