我有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
我试着用你所建议的母体实体的addChildObject()替换setMother(),但仍然是:CoreData:error:(19)constraint failed ... help! – Guaido79
请为您的Child和Mother对象发布.h文件。 – timthetoolman
该类是使用Xcode自动生成的,我发布了代码,感谢您的帮助。 – Guaido79