Ios 从子上下文分配对象时试图建立关系的非法尝试

Ios 从子上下文分配对象时试图建立关系的非法尝试,ios,objective-c,core-data,nsmanagedobjectcontext,Ios,Objective C,Core Data,Nsmanagedobjectcontext,我花了几个小时试图解决父子核心数据模型的问题。但让我们从头开始。我有主上下文和子上下文,主上下文是.parentContext - (NSManagedObjectContext *)mainContext { if (!_mainContext) { _mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType]; [_m

我花了几个小时试图解决父子核心数据模型的问题。但让我们从头开始。我有主上下文和子上下文,主上下文是
.parentContext

- (NSManagedObjectContext *)mainContext {
    if (!_mainContext) {
        _mainContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_mainContext setPersistentStoreCoordinator:self.persistentStoreCoordinator];
    }
    return _mainContext;
}

- (NSManagedObjectContext *)childContext {
    if (!_childContext) {
        _childContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
        [_childContext setParentContext:self.mainContext];
    }
    return _childContext;
}
接下来,我在分离的上下文中创建两个对象

Entity2 *entity2 = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Entity2 class]) 
                                                 inManagedObjectContext:_stack.childContext];

Entity1 *entity1 = [NSEntityDescription insertNewObjectForEntityForName:NSStringFromClass([Entity1 class])
                                                 inManagedObjectContext:_stack.mainContext];
entity1.arg1 = @"ABC";
entity1.arg2 = @"DEF";
这里一切都好

然后,我想将一个对象添加到另一个对象的关系中,不管我是尝试将
entity1
添加到
entity2
还是相反

[entity1 setEntity2:entity2];
在的文章中,我读到我应该用save操作执行block,因为对象彼此不认识。看起来是这样的:

[_stack.childContext performBlock:^{
    NSError *error;
    if (![_stack.childContext save:&error]) {
        NSLog(@"Error: %@", error);
    }

    [_stack.mainContext performBlock:^{
        NSError *error;
        if (![_stack.mainContext save:&error]) {
            NSLog(@"Error: %@", error);
        }

        [entity1 setEntity2:entity2];
    }];
}];
但无论我把
[entity1 setEntity2:entity2]
放在哪里,它都以:

2014-06-22 08:48:24.444 MultiContextualCoreData[1324:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'entity1' between objects in different contexts (source = <Entity2: 0x8c81570> (entity: Entity2; id: 0x8c80000 <x-coredata:///Entity2/tC31696AE-0A0A-424E-9C8E-1E19085F3FB43> ; data: {
    entity1 = nil;
}) , destination = <Entity1: 0x8c80200> (entity: Entity1; id: 0x8c80250 <x-coredata:///Entity1/tC31696AE-0A0A-424E-9C8E-1E19085F3FB42> ; data: {
    arg1 = ABC;
    arg2 = DEF;
    entity2 = nil;
}))'
*** First throw call stack:
(
    0   CoreFoundation                      0x01b541e4 __exceptionPreprocess + 180
    1   libobjc.A.dylib                     0x018d38e5 objc_exception_throw + 44
    2   CoreData                            0x00293b7e _PFManagedObject_coerceValueForKeyWithDescription + 3614
    3   CoreData                            0x002614e9 _sharedIMPL_setvfk_core + 185
    4   CoreData                            0x0027ada7 _svfk_0 + 39
    5   MultiContextualCoreData             0x00002d4a -[AppDelegate test] + 554
    6   MultiContextualCoreData             0x00002acd -[AppDelegate application:didFinishLaunchingWithOptions:] + 605
    7   UIKit                               0x0058d14f -[UIApplication _handleDelegateCallbacksWithOptions:isSuspended:restoreState:] + 309
    8   UIKit                               0x0058daa1 -[UIApplication _callInitializationDelegatesForURL:payload:suspended:] + 1810
    9   UIKit                               0x00592667 -[UIApplication _runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:] + 824
    10  UIKit                               0x005a6f92 -[UIApplication handleEvent:withNewEvent:] + 3517
    11  UIKit                               0x005a7555 -[UIApplication sendEvent:] + 85
    12  UIKit                               0x00594250 _UIApplicationHandleEvent + 683
    13  GraphicsServices                    0x03a07f02 _PurpleEventCallback + 776
    14  GraphicsServices                    0x03a07a0d PurpleEventCallback + 46
    15  CoreFoundation                      0x01acfca5 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 53
    16  CoreFoundation                      0x01acf9db __CFRunLoopDoSource1 + 523
    17  CoreFoundation                      0x01afa68c __CFRunLoopRun + 2156
    18  CoreFoundation                      0x01af99d3 CFRunLoopRunSpecific + 467
    19  CoreFoundation                      0x01af97eb CFRunLoopRunInMode + 123
    20  UIKit                               0x00591d9c -[UIApplication _run] + 840
    21  UIKit                               0x00593f9b UIApplicationMain + 1225
    22  MultiContextualCoreData             0x00002efd main + 141
    23  libdyld.dylib                       0x0219b701 start + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 
2014-06-22 08:48:24.444多上下文编码数据[1324:60b]***由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“非法尝试在不同上下文中的对象之间建立关系“entity1”(源=(实体:Entity2;id:0x8c80000;数据:{
实体1=无;
}),destination=(实体:Entity1;id:0x8c80250;数据:{
arg1=ABC;
arg2=DEF;
实体2=无;
}))'
***第一次抛出调用堆栈:
(
0 CoreFoundation 0x01b541e4例外预处理+180
1 libobjc.A.dylib 0x018d38e5 objc_异常_抛出+44
2个CoreData 0x00293b7e _PFManagedObject_强制评估值forkey,带说明+3614
3 CoreData 0x002614e9_sharedIMPL_setvfk_core+185
4 CoreData 0x0027ada7_svfk_0+39
5多上下文编码数据0x00002d4a-[AppDelegate测试]+554
6多上下文数据0x00002acd-[AppDelegate应用程序:didFinishLaunchingWithOptions:+605
7 UIKit 0x0058d14f-[UIApplication\u处理的远程回调,带选项:isSuspended:restoreState:+309
8 UIKit 0x0058daa1-[UIApplication\u CallInitializationDelegatesForRL:有效负载:挂起:][1810
9 UIKit 0x00592667-[UIApplication-runWithURL:payload:launchOrientation:statusBarStyle:statusBarHidden:+824
10 UIKit 0x005a6f92-[UIApplication handleEvent:withNewEvent:][3517
11 UIKit 0x005a7555-[UIApplication sendEvent:+85
12 UIKit 0x00594250 _UIApplicationHandleEvent+683
13图形服务0x03a07f02 _PurpleEventCallback+776
14图形服务0x03a07a0d PurpleEventCallback+46
15 CoreFoundation 0x01acfca5\uuuuu CFRUNLOOP\u正在调用\uu OUT\uu以执行\uu功能\uuuu+53
16 CoreFoundation 0x01acf9db\uuu CFRunLoopDoSource1+523
17 CoreFoundation 0x01afa68c\uuu CFRunLoopRun+2156
18 CoreFoundation 0x01af99d3 CFRunLoopRunSpecific+467
19 CoreFoundation 0x01af97eb CFRUNLOOPSRUNINMODE+123
20 UIKit 0x00591d9c-[UIU应用程序运行]+840
21 UIKit 0x00593f9b UIApplicationMain+1225
22多上下文编码数据0x00002efd main+141
23 libdyld.dylib 0x0219b701启动+1
)
libc++abi.dylib:以NSException类型的未捕获异常终止
(lldb)
我做错了什么


提前感谢您的帮助。

问题是两个对象必须属于同一上下文才能在它们之间建立关系。在您的例子中,其中一个上下文有一个私有类型,它有自己的工作队列,其中主上下文在主队列上工作。这是一种防止您在将来遇到并发问题的方法

可能的解决办法是

  • 创建
    entity1
    ,保存主上下文,使用
    managedObjectID
    在子上下文中检索它,或者如果提取请求更有意义,则只在
    entity1
    entity2
    在同一上下文中时才建立关系
  • 或者,如果逻辑允许,简单地在同一上下文中创建两个对象

谢谢,这对我帮助很大。我使用第一种情况(使用
NSManagedObjectID
获取对象),因为我无法在同一上下文中创建这些对象。我使用属性注入在同一上下文(选项2)中创建了这两个对象,解决了问题,thanks@Naishta你能举例说明你是如何在同一个环境中创建对象的吗?