2012-05-23 44 views
0

我有2个实体:母亲和孩子。 母亲有它的属性和其他NSSet作为孩子。 孩子有它的财产和其他一个母亲的财产。 所以有关系1-n: 现在,母亲已经保存并持续 d。我需要插入一个新的孩子,所以我尝试用代码:IOS - CoreData - 插入已插入关系实体的新实体

-(void)addChild:(NSString *)name { 
    // get Child instance to save 
     Child *child = (Child*) [NSEntityDescription insertNewObjectForEntityForName:@"Child" inManagedObjectContext:self.managedObjectContext]; 
     mother 

     // get Mother element to associate 
     NSFetchRequest *request = [[NSFetchRequest alloc] init]; 
     NSEntityDescription *entity = [NSEntityDescription entityForName:@"Mother" inManagedObjectContext:self.managedObjectContext]; 
     [request setEntity:entity]; 
     NSPredicate *predicate = [NSPredicate predicateWithFormat:@"mother_desc = %@", @"themothertofind"]; 
     [request setPredicate:predicate]; 

     id sortDesc = [[NSSortDescriptor alloc] initWithKey:@"mother_desc" ascending:YES]; 
     [request setSortDescriptors:[NSArray arrayWithObject:sortDesc]]; 

     NSError *error = nil; 
     NSArray *fetchResults = [self.managedObjectContext executeFetchRequest:request error:&error]; 
     if (fetchResults == nil) { 
      NSLog(@"%@", [error description]); 
     } 
     else { 
     // id mother exist associate to Child 
      [child setMother:[fetchResults objectAtIndex:0]]; 
      NSLog(@"Mother: %@", Child.mother.mother_desc); 
     } 


     [child setName:name]; 

     if (![self.managedObjectContext save:&error]) { 
      NSLog(@"%@", [error description]); 
     } 
} 

随着日志我看到所有数据的一致性。 不幸的是我收到一个约束异常(19)。就像CoreData尝试再次保存Mother对象一样。
有人可以看到代码中的错误在哪里?

谢谢!

@class Mother; 

@interface Child : NSManagedObject 

@property (nonatomic, retain) NSString * name; 
@property (nonatomic, retain) Mother *mother; 

@end 

@class Child; 

@interface Mother : NSManagedObject 

@property (nonatomic, retain) NSString * name; 
@property (nonatomic, retain) NSSet *children; 
@end 

@interface Mother (CoreDataGeneratedAccessors) 

- (void)addChildrenObject:(Child *)value; 
- (void)removeChildrenObject:(Child *)value; 
- (void)addChildren:(NSSet *)values; 
- (void)removeChildren:(NSSet *)values; 

@end 

回答

0

我已经找到了问题:

在我添加的记录,而无需使用CoreData表zchild。

这会导致表z_primarykey(由CoreData生成的表自动更新)未更新。在具体的,有一个列“z_max”,必须包含下一个插入的下一个ID。在我的情况下,这些z_max等于已经在表中的孩子的ID,这是违反约束。

1

而不是设置儿童托管对象的母亲属性,添加到母亲管理对象的一组儿童的孩子。但请注意,您不能简单地获得对该集的引用并添加它,您需要使用适当的方法。

母亲管理对象,假设你设置了正确的模型,应该有一个沿着addChildObject:或addChildrenObject:的方法。

所以在代码看起来沿着n此线:

Mother *mother=[fetchResults objectAtIndex:0]; 
NSLog(@"mother: %@, mother); 
[mother addChildrenObject: child]; 
NSLog(@"Mother: %@", child.mother.mother_desc); 

注意,我做了一个修正到原来的NSLog声明。您实际上是要求从该类中进行描述,而不是在该子对象的实例中。无论哪种方式,当使用Mother管理对象的方法将项目添加到其子集时,核心数据还将设置子项的母属性的反向关系。

祝你好运。

+0

我试着用你所建议的母体实体的addChildObject()替换setMother(),但仍然是:CoreData:error:(19)constraint failed ... help! – Guaido79

+1

请为您的Child和Mother对象发布.h文件。 – timthetoolman

+0

该类是使用Xcode自动生成的,我发布了代码,感谢您的帮助。 – Guaido79