我遇到了这个令人讨厌的崩溃和错误。
运行此代码时发生崩溃:
Address *address = [[Address alloc] initWithEntity:[NSEntityDescription entityForName:@"Address" inManagedObjectContext:managedObjectContext] insertIntoManagedObjectContext:nil];
//Crashes here!
[person addAddressObject:address];
Illegal attempt to establish a relationship 'person' between objects in different contexts
整个控制台错误如下。
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'person' between objects in different contexts (source = <Address: 0x1f87e270> (entity: Address; id: 0x1f87e2b0 <x-coredata:///Address/t748EE284-0311-4489-9654-1D902EB0D4CC2> ; data: {
addressLine1 = "";
addressLine2 = "";
addressLine3 = "";
city = "";
country = "";
person = nil;
state = "";
title = "";
zip = "";
}) , destination = <Person: 0x1ed9e1e0> (entity: Person; id: 0x1ed9c710 <x-coredata://ED0283A9-A847-407E-BFEC-CF2BF85C6A9C/Person/p1> ; data: {
address = (
"0x1f87e2b0 <x-coredata:///Address/t748EE284-0311-4489-9654-1D902EB0D4CC2>",
"0x1ed93e70 <x-coredata://ED0283A9-A847-407E-BFEC-CF2BF85C6A9C/Address/p1>"
);
favourite = nil;
firstName = Josh;
lastName = Kahane;
}))'
我不知道如何解决这个问题。大概它认为有两个不同的 managedObjectContexts?但是,在我的应用程序中,我只像这样引用在我的应用程序委托(delegate)中所做的(在 viewDidLoad 运行):
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@", managedObjectContext);
}
关于从哪里开始寻找差异的任何想法?谢谢。
编辑:
新发现。就在应用程序崩溃之前,我已经 NSLogged 地址和人员管理的对象上下文。结果证明地址上下文是
(null)
,即使我事先运行检查以设置上下文,如果它为零。 最佳答案
您将其插入到 nil managedObjectContext
中。
您需要将对象插入到用于实体的 NSManagedObjectContext
中。即 managedObjectContext
。
在 Address 对象的 alloc init 中。
在 OP 中阅读您的评论。
你要么...
保存所有必需的值,然后在确认时创建地址对象并一次性插入所有内容。
或者...
创建对象并插入它创建所有关系,然后如果用户按下取消,则删除该对象。
我会做这两个之一来避免这个错误。
关于iphone - 非法尝试建立关系,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13705718/