2013-04-26 67 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