我有 2 个实体:母亲和孩子。母亲有它的属性和其他的 NSSet 作为孩子。孩子有它的财产和其他的母亲财产。所以有关系 1-n:现在,母亲已经被拯救并坚持了 d。我需要插入一个新的孩子,所以我尝试使用代码:
-(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