gpt4 book ai didi

ios - 在后台线程上保存到 CoreData Context

转载 作者:技术小花猫 更新时间:2023-10-29 11:13:02 25 4
gpt4 key购买 nike

我为此苦苦挣扎了一段时间,Apple 的文档和 SO 到目前为止都没有帮助。我在 UIManagedDocument 上使用 ManagedObjectContext,下面的代码工作正常。然后我决定在 AppDelegate 中使用 Apple 的 CoreData 模板,因此在 AppDelegate 中创建模型、持久存储协调器和上下文。使用 AppDelegate 的上下文获取是没有问题的,但是后台保存是一个问题。我应该在我正在保存的线程上有本地上下文,并且按照 Apple 的要求有相同的持久性存储协调器。但是下面的代码实际上并没有保存数据。这里有人可以建议吗?谢谢。

- (void)fetchAndPersist
{
dispatch_queue_t ffetchQ = dispatch_queue_create("ForFetch", NULL);
dispatch_async(ffetchQ, ^{

NSManagedObjectContext *secureManagedObjectContext;
NSPersistentStoreCoordinator *coordinator = [appDelegate persistentStoreCoordinator];
if (coordinator != nil) {
secureManagedObjectContext = [[NSManagedObjectContext alloc] init];
[secureManagedObjectContext setPersistentStoreCoordinator:coordinator];
}

// find missing date
DataManager *dataManager = [[DataManager alloc] init];
NSDate *missingDate = [dataManager findMissingDateFromDate:selectedDate inContext:secureManagedObjectContext];

if (missingDate) {
// fetch and parse data
DataFetcher *dataFetcher = [[dataFetcher alloc] init];
NSDictionary *fetchResponse = [dataFetcher parseDataForDate:missingDate];

// persist it in a block and wait for it
[secureManagedObjectContext performBlock:^{
DataStore *dataStore = [[DataStore alloc] init];
BOOL parsingError = [dataStore persistData:fetchResponse inContext:secureManagedObjectContext];

if (parsingError) {
// handle error
} else {
dispatch_async(dispatch_get_main_queue(), ^{
// perform on main
[self fetchAndPersist];
});
}
}];
}
});
}

最佳答案

尝试使用父/子上下文:

http://www.cocoanetics.com/2012/07/multi-context-coredata/

在上面的链接中,您可以找到代码示例。

关于ios - 在后台线程上保存到 CoreData Context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18812130/

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