Objective c IOS-CoreData-使用已插入的关系实体插入新实体
我有两个实体:母亲和孩子。 母亲有它的财产和其他作为孩子的财产。 孩子有自己的财产,其他的则有母亲的财产。 因此,存在关系1-n: 现在,母亲已经得救并坚持下去了 D我需要插入一个新的子项,因此我尝试使用以下代码:Objective c IOS-CoreData-使用已插入的关系实体插入新实体,objective-c,ios,core-data,Objective C,Ios,Core Data,我有两个实体:母亲和孩子。 母亲有它的财产和其他作为孩子的财产。 孩子有自己的财产,其他的则有母亲的财产。 因此,存在关系1-n: 现在,母亲已经得救并坚持下去了 D我需要插入一个新的子项,因此我尝试使用以下代码: -(void)addChild:(NSString *)name { // get Child instance to save Child *child = (Child*) [NSEntityDescription insertNewObjectForEn
-(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再次尝试保存母对象一样。有人可以看到代码中的错误在哪里 谢谢
@class Mother;
@interface Child : NSManagedObject
@property (nonatomic, retain) NSString * name;
@property (nonatomic, retain) Mother *mother;
@end
不要设置子托管对象的母属性,而是将子对象添加到母托管对象的子对象集中。但是请注意,您不能简单地获取对集合的引用并添加它,您需要使用适当的方法 假设您正确设置了模型,则母托管对象应该具有一个与addChildObject:或addChildrenObject:类似的方法 因此,在代码中,可以看到以下内容:
Mother *mother=[fetchResults objectAtIndex:0];
NSLog(@"mother: %@, mother);
[mother addChildrenObject: child];
NSLog(@"Mother: %@", child.mother.mother_desc);
请注意,我对您最初的NSLog声明进行了更正。实际上,您要求的是类的描述,而不是子对象实例中的描述
无论哪种方式,当使用母托管对象的方法向其子对象集添加项时,核心数据也将设置子对象的母属性的反向关系
祝你好运
蒂姆我发现了问题: 在表zchild中,我添加了记录,但没有使用CoreData
这导致表z_primarykey(由CoreData自动生成的表)未更新。在特定字段中,有一列“z_max”,它必须包含下一个用于下一次插入的id。在我的例子中,这些z_max等于表中已经存在的子项的id,这就是约束冲突。我尝试用您建议的母亲实体的addChildObject()替换setMother(),但仍然:CoreData:error:(19)约束失败。。。救命啊!请为您的子对象和母对象发布.h文件。该类是使用Xcode自动生成的,我已经发布了代码,感谢您的帮助。我发现了问题:在表zchild中,我添加了记录,但没有使用CoreData。这导致表z_primarykey(由CoreData自动生成的表)未更新。在特定字段中,有一列“z_max”,它必须包含下一个用于下一次插入的id。在我的例子中,这些z_max等于表中已经存在的子项的id,这就是约束冲突。谢谢你的帮助,很好。看起来你找到了核心数据的圣杯。不要自己修改数据库。如果我的回答修正了你原来的问题,请接受。
Mother *mother=[fetchResults objectAtIndex:0];
NSLog(@"mother: %@, mother);
[mother addChildrenObject: child];
NSLog(@"Mother: %@", child.mother.mother_desc);