保存到CoreData上下文中的背景线程 [英] Saving into CoreData Context on background thread

查看:151
本文介绍了保存到CoreData上下文中的背景线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我现在正在努力与这一段时间,苹果的文档和SO没有帮助到目前为止。我在一个UIManagedDocument上使用ManagedObjectContext,下面的代码工作正常。然后我决定在AppDelegate中使用Apple的模板用于CoreData,因此在AppDelegate中创建模型,持久存储协调器和上下文。获取AppDelegate的上下文没有问题,但是后台保存是一个问题。我应该在我保存的线程上的本地上下文和根据苹果有相同的持久性存储协调器。但是下面的代码并不实际保存数据。这里有人可以咨询吗?谢谢。

I am struggling with this for some time now and Apple's documentation and SO did not help so far. I was using ManagedObjectContext on a UIManagedDocument and the code below worked fine. I then decided to use Apple's template for CoreData in AppDelegate, so model, persistent store coordinator and context is created in AppDelegate. Fetching with AppDelegate's context is no problem, but background saving is an issue. I should have local context on the thread I am saving and as per Apple to have same persistance store coordinator. But the code below does not actually save the data. Can someone here please advise? Thank you.

- (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 / ,您可以在这里找到代码示例。

Try to use parent / child contexts. http://www.cocoanetics.com/2012/07/multi-context-coredata/ here you can find a code sample.

这篇关于保存到CoreData上下文中的背景线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆