【问题标题】:Core Data concurrency type not working as expectedCore Data 并发类型未按预期工作
【发布时间】:2013-03-01 01:14:56
【问题描述】:

根据 Apple,我在 App Delegate 中创建核心数据堆栈,然后将 managedObjectContext 传递给我的第一个控制器,然后从那里传递给第二个控制器,依此类推。

我正在尝试在后台线程中做一些工作并想使用 PrivateConcurrency 类型,但我收到错误消息,即父级必须是 Main 或 Private。

在应用委托中我创建上下文

- (NSManagedObjectContext *)managedObjectContext
{
    if (_managedObjectContext != nil) {
        return _managedObjectContext;
    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil) {
        _managedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
        [_managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return _managedObjectContext;
}

然后我将它传递给我的第一个控制器

UINavigationController *navigationController = (UINavigationController *)self.window.rootViewController;
Paperwoven_LoadingViewController *firstController = (Paperwoven_LoadingViewController *)navigationController.topViewController;
[firstController setManagedObjectContext:[self managedObjectContext]];
NSLog(@"concurrency type is %@", [self managedObjectContext]);
NSLog(@"concurrency type is %u",firstController.managedObjectContext.concurrencyType);

我可以看到,当我从 self 注销并发类型时,我得到 2,即 Main。但是当我检查我刚刚发送到第一个控制器的上下文时,我得到 0。为什么它没有正确传递?

编辑

此外,我可以通过AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate] 获取 managedObjectContext,我可以看到并发类型是 MAIN,但如果在下一行我做 self.managedObjectContext = appDelegate.managedObjectContext,然后检查 self.managedObjectContext 上的并发类型,它是 0。看起来像分配它从 App 委托到控制器丢失并发类型。

【问题讨论】:

    标签: ios objective-c xcode core-data


    【解决方案1】:

    从您的代码中,最可能的解释是 firstController 为零。你用这条线得到它:

    Paperwoven_LoadingViewController *firstController = (Paperwoven_LoadingViewController *)navigationController.topViewController;
    

    但如果topViewController 为零,那么firstViewController 为零。在以下几行中:

    [firstController setManagedObjectContext:[self managedObjectContext]];
    NSLog(@"concurrency type is %@", [self managedObjectContext]);
    NSLog(@"concurrency type is %u",firstController.managedObjectContext.concurrencyType);
    

    在 Objective-C 中向 nil 发送消息不是错误,因此第一行是空操作。在上面的最后一行中,您打印的是 nil.managedObjectContext.concurrencyType,它将是 0。

    这看起来不像是核心数据问题——更像是配置视图控制器的问题。

    【讨论】:

    • 如果我注销 [navigationController.topViewController 类] 我得到了正确的类。如果控制器为 nil,那不就是 nil 或空吗?
    • 感谢汤姆的建议。最好的起点是确保你的对象不是 nil 并且是你所期望的。最后,即使他们当时没有使用核心数据,原始开发人员也不知道在基本控制器中设置了核心数据堆栈。所以那些与我的堆栈冲突
    【解决方案2】:

    我是个白痴,有点。另一位开发人员将所有控制器都具有的相同核心数据堆栈方法放在 Base 控制器中。发生的事情是我能够设置控制器上下文,但随后基本控制器将创建自己的上下文并覆盖传入的上下文。删除此垃圾代码解决了我的问题。这回答了我的问题,所以我将关闭它。请不要投反对票,我们都有过编码脑放屁的经历。

    【讨论】:

      猜你喜欢
      • 2017-02-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-25
      相关资源
      最近更新 更多