gpt4 book ai didi

objective-c - IOS - CoreData - 插入具有已插入关系实体的新实体

转载 作者:行者123 更新时间:2023-11-29 04:38:32 26 4
gpt4 key购买 nike

我有 2 个实体:母亲和 child 。母亲拥有它的属性以及其他 NSSet 作为 child 的属性。 child 拥有它的属性(property),而其他属性(property)则拥有母亲的属性(property)。于是就有关系式1-n:现在,母亲已经得救并坚持下去d.我需要插入一个新的 child ,所以我尝试使用代码:

-(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

最佳答案

不要设置子管理对象的 mother 属性,而是将子对象添加到 Mother 管理对象的子对象集中。但请注意,您不能简单地获取对该集的引用并添加它,您需要使用适当的方法。

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

因此,在代码中会看到以下内容:

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

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

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

祝你好运。

蒂姆

关于objective-c - IOS - CoreData - 插入具有已插入关系实体的新实体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10727559/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com