我有一个关于核心数据的基本问题。
我有两张桌子一对多。
我已经设置了应用程序以将子级添加到父级,但我无法理解如何设置关系,以便当我通过视图控制器添加新子级时,它将子级添加到正确的父级。
我已经生成了实体子类,并设法让应用程序添加一个子类(但它将它添加到索引 0),但我似乎无法使用找到正确父级的 fetchrequest。
- (IBAction)save:(id)sender {
NSManagedObjectContext *context = [self managedObjectContext];
Child *newChild = [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:context];
[newChild setValue:self.childName.text forKey:@"childName"];
[newChild setValue:self.born.text forKey:@"born"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"ParentList" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
ParentList *parent = [fetchedObjects objectAtIndex:0]; //this adds it to the first parentList in list at index 0 not to the correct parent
NSLog(@"parent: %@ created", league);
[parent addChildObject: newChild];
//
///////////////////////////////////////////
//////index path is wrong//////////////////
///////////////////////////////////////////
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
}
[self dismissViewControllerAnimated:YES completion:nil];
}