gpt4 book ai didi

ios - NSOperation 中的 ASINetworkQueue 错误保存核心数据

转载 作者:行者123 更新时间:2023-11-28 17:40:11 28 4
gpt4 key购买 nike

我想在 NSOperation 中使用 ASINetworkQueue。这很好用,没有问题。失败的是保存核心数据。我为这个操作设置了一个新的 NSManagedObjectContext,就像文档中所说的那样。

我认为问题在于我在 ASINetworkQueue 完成并调用委托(delegate)选择器时保存了数据。因为在 mainThread 上调用了委托(delegate),所以保存消息失败。

这会是问题所在吗?有人有解决方案吗?

最佳答案

您正在正确使用 PerformSelectorOnMainThread 方法(合并来自新实例化的 ManagedObjectContext 的更改)?

我在我的操作中做了类似的事情(ctx 是我实例化的 MOC):

首先注册通知:

// Register context with the notification center
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];

[nc addObserver:self
selector:@selector(mergeChanges:)
name:NSManagedObjectContextDidSaveNotification
object:ctx];

然后当你需要保存上下文时:

if ([ctx hasChanges]) {
error = nil;

// Save the context.
if (![ctx save:&error])
{
// Do something with the error
}

// Clear out the scratchpad
[ctx reset];

}

然后是与主 MOC 合并的方法:

- (void)mergeChanges:(NSNotification *)notification
{
id appDelegate = [[UIApplication sharedApplication] delegate];

NSManagedObjectContext *mainContext = [appDelegate managedObjectContext];
// Merge changes into the main context on the main thread
[mainContext performSelectorOnMainThread:@selector(mergeChangesFromContextDidSaveNotification:)
withObject:notification
waitUntilDone:NO];
// NSLog(@"Merged Changes");
}

希望对你有帮助

关于ios - NSOperation 中的 ASINetworkQueue 错误保存核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8508249/

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