0

我有 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
4

2 回答 2

1

与其设置子托管对象的母属性,不如将子添加到母托管对象的子集。但请注意,您不能简单地获取对集合的引用并添加它,您需要使用适当的方法。

假设您正确设置模型,Mother 托管对象应该有一个类似于 addChildObject: 或 addChildrenObject: 的方法。

所以在代码中会看起来沿着以下几行:

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

请注意,我对您原来的 NSLog 语句进行了更正。您实际上是在要求类的描述,而不是子对象的实例。

无论哪种方式,当使用 Mother 托管对象的方法将项目添加到其子集时,Core data 也会设置孩子的母亲属性的反向关系。

祝你好运。

蒂姆

于 2012-05-23T21:00:01.290 回答
0

我发现了问题:

在表 zchild 中,我在不使用 CoreData 的情况下添加了记录。

This cause the table z_primarykey (a table auto generated by CoreData) was not updated. In the specific, there is a column "z_max" that must contains the next id to use for the next insertion. In my case those z_max are equals to the id of child already in table and that's the constraint violation.

于 2012-05-24T21:10:28.353 回答