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

 手机用户2502863297 发布于 2023-01-08 10:58

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

在多语境核心数据的文章中| 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];
    }];
}];

但无论我把[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 =  (entity: Entity2; id: 0x8c80000  ; data: {
    entity1 = nil;
}) , destination =  (entity: Entity1; id: 0x8c80250  ; 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) 

我在这里做错了什么?

提前感谢您的帮助.

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

    可能的解决办法是

    创建entity1,保存主上下文,使用managedObjectID或者获取请求在子上下文中检索它,如果它更有意义,只有当你有entity1entity2在同一个上下文时建立关系

    或者,简单地说,如果您的逻辑允许,则在相同的上下文中创建两个对象.

    2023-01-08 11:00 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有