2013-04-26 73 views
0

我有一个关于核心数据的一个基本问题。核心数据父子关系

我有2个表一对多。

我有安装的应用程序给孩子添加到父,但我不明白我是如何设置的关系,这样,当我通过它增加了孩子正确的父视图控制器中添加一个新的子。

我已经生成了实体子类,并设法让应用程序添加一个孩子(但它将它添加到索引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]; 

}

回答

0

您需要通过父母的objectID到第二视图控制器(如果我理解正确的设置)。
取在其他视图上下文父(使用existingObjectWithID:error:所述的NSManagedObjectContext的)。
将父子代设置为提取的对象。

应该是这个样子:

NSError* error = nil; 
NSManagedObjectID* parentID = //the parent object id you selected 
Parent* parent = [context existingObjectWithID:parentID error:&error]; 
if (parent) { //parent exists 
    Child *newChild = [NSEntityDescription insertNewObjectForEntityForName:@"Child" 
                inManagedObjectContext:context]; 
    [newChild setValue:self.childName.text forKey:@"childName"]; 
    [newChild setValue:self.born.text forKey:@"born"]; 
    [newChild setValue:parent forKey:@"parent"];//Set the parent 
} else { 
    NSLog(@"ERROR:: error fetching parent: %@",error); 
} 

编辑:

获取所选对象ID(假设你使用的是NSFetchedReaultsController):

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSManagedObject *object = [[self fetchedResultsController] objectAtIndexPath:indexPath]; 
    //Use object.objectID as the selected object id to pass to the other view controller 
    //what ever you need to do with the object 
} 
+0

我在阅读教程之前遇到ObjectID,但是我o显然需要阅读和学习更多。为了更多地解释,我有两个表视图,每个视图都有一个输入视图控制器,用于添加父文本和子文本。我可以将数据输入到父项中,但我需要找到在父项中选择的ObjectID并将其传递给子表视图控制器,然后将其传递给子项文本视图控制器。你能解释更多关于如何从父级选定的行获取对象ID并通过prepareforsegue传递它吗? – 2013-04-26 20:57:22