我遇到了这个令人讨厌的崩溃和错误。
运行此代码时发生崩溃:
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?但是,在我的应用程序中,我只引用了我的应用程序委托中的内容(在 viewDidLoad 处运行):
if (managedObjectContext == nil)
{
managedObjectContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(@"After managedObjectContext: %@", managedObjectContext);
}
关于从哪里开始寻找差异的任何想法?谢谢。
编辑:
新发现。就在应用程序崩溃之前,我已经对地址和人员管理的对象上下文进行了 NSLogged。原来地址上下文是(null)
,即使我事先运行检查以设置上下文(如果它为零)。