我在详细视图控制器中创建新的子实体。所以我发送了segue
detailedViewController.managedObjectContext = managedObjectContext;
detaledViewController.parent = currentParent; //type of Parent
在detailViewController.m
-(IBAction)saveChildObj:(id)sender{
self.childEntity= [NSEntityDescription insertNewObjectForEntityForName:@"ChildEntity" inManagedObjectContext:self.managedObjectContext];
self.childEntity.childEntityName= self.childEntityName.text;
[self.parent addMyChildObject:self.childEntity];
[self.managedObjectContext performBlockAndWait:^{
NSError *error = nil;
BOOL saved = [self.managedObjectContext save:&error];
if (!saved) {
// do some real error handling
NSLog(@"Could not save Date due to %@", error);
}
[[osCoreDataController sharedImstanse] saveMasterContext];
}];
[self.navigationController popViewControllerAnimated:YES];
}
调用addMyChildEntity后,我的文本错误:
2013-06-09 22:21:39.191 FindYourMedicine[2476:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'parent' between objects in different contexts (source = <ChildEntity: 0x8acbf30> (entity: ChildEntity; id: 0x8accb10 <x-coredata:///ChildEntity/t8DB5D204-A359-45E5-8F2B-8DE6A26D245C3> ; data: {
date = (
);
parent= nil;
childEntityName= fgh;
times = (
);
}) , destination = <Parent: 0x8a9a9a0> (entity: Parent; id: 0x8a99cb0 <x-coredata://48BBE637-9D07-4529-9C6A-DCCF118B4717/Disease/p2> ; data: {
parentName = "\U0430\U0441\U0442\U043c\U0430";
childEntity= (
);
核心数据的结构对很多人来说是:父母 - &gt;&gt;儿童 - &gt;&gt;次
我尝试使用managedObjectContext.parantContext但没有任何帮助
答案 0 :(得分:0)
不要传递托管对象上下文,只需传递父对象。然后,当您需要添加子项时,只需向父项询问其托管对象上下文(所有托管对象都具有此属性)。