I have a One-To-Many relationship set up in core data. I can View/Add/Remove objects from the ‘Main’ Entity, however now I want to View/Add/Remove objects to the many ‘Subs’ entity which should have separate lists of Subs objects for each Main entity.
I have tried this code:
NSManagedObjectContext *context = [[DataSingleton sharedSingleton] thisMain].managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"Subs" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
wolArray = [NSMutableArray arrayWithArray:fetchedObjects];
[[DataSingleton sharedSingleton] thisMain] is the Main that i’m trying to get the Subs for. Am I doing this wrong?
It just seems to give me all the Subs for all the Mains.
Now it is possible that maybe i’m adding them wrong, and they are not getting added to a Subs off of a Main (If thats even possible?)
This is how I’ve added them:
NSManagedObjectContext *context = [[DataSingleton sharedSingleton] thisMain].managedObjectContext;
Subs *subsInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"Subs"
inManagedObjectContext:context];
subsInfo.name = [newDevice objectForKey:@"name"];
subsInfo.address = [newDevice objectForKey:@"address"];
subsInfo.post = [newDevice objectForKey:@"post"];
NSError *error;
if (![context save:&error]) {
NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
}
If
thisMainis a “Main” object andsubsis the one-to-many relation from “Main” to “Subs”, then you can just doto get an array of all “Subs” for
thisMain. Do do not need a fetch request for that.For your second task you need to define an inverse relation “main” from “Subs” to “Main”. When you have created the new “Subs” object
subsInfo, thenadds it to the main object.