gpt4 book ai didi

ios - 核心数据并发类型未按预期工作

转载 作者:行者123 更新时间:2023-11-29 04:06:16 25 4
gpt4 key购买 nike

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

我尝试在后台线程中执行一些工作,并希望使用 PrivateConcurrency 类型,但收到错误消息,指出父级必须是 Main 或 Private。

在应用程序委托(delegate)中,我创建上下文

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

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

然后我将它传递给我的第一个 Controller

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。但是当我检查刚刚发送到第一个 Controller 的上下文时,我得到 0。为什么它没有正确传递?

编辑

此外,我可以通过 AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate] 获取 ManagedObjectContext我可以看到并发类型是 MAIN 但如果在下一行我这样做 self.managedObjectContext = appDelegate.managedObjectContext然后检查 self.managementObjectContext 上的并发类型,它是 0。看起来将其从 App delegate 分配给 Controller 会丢失并发类型。

最佳答案

从您的代码来看,最可能的解释是 firstController 为零。你可以使用这一行得到它:

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

但是如果 topViewController 为 nil,则 firstViewController 为 nil。在以下几行中:

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

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

这看起来不像是核心数据问题——更像是配置 View Controller 的问题。

关于ios - 核心数据并发类型未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15148776/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com