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

Tom*_*ulc 2 core-data objective-c nsmanagedobjectcontext ios

我花了几个小时试图解决父子核心数据模型的问题.但是,让我们从头开始.我有主要的上下文和子上下文.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;
}
Run Code Online (Sandbox Code Playgroud)

接下来,我在分离的上下文中创建两个对象.

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";
Run Code Online (Sandbox Code Playgroud)

一切都好.

然后我想将一个对象添加到另一个对象的关系中,无论我是否尝试添加entity1,entity2反之亦然.

[entity1 setEntity2:entity2];
Run Code Online (Sandbox Code Playgroud)

多语境核心数据的文章中| Cocoanetics我读过我应该用保存操作执行块,因为对象不相互了解.所以它看起来像这样:

[_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];
    }];
}];
Run Code Online (Sandbox Code Playgroud)

但无论我把[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) 
Run Code Online (Sandbox Code Playgroud)

我在这里做错了什么?

提前感谢您的帮助.

Sas*_*ats 7

问题是两个对象必须属于同一个上下文才能建立它们之间的关系.在您的情况下,其中一个上下文具有私有类型,它有自己的队列,主要上下文在主队列上工作.这是一种保护您在未来遇到并发问题的方法.

可能的解决办法是

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