在后台线程上保存到CoreData Context

Mar*_*les 9 multithreading core-data objective-c ios

我现在正在努力解决这个问题,到目前为止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];
                    });
                }
            }];
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

Svi*_*miv 18

尝试使用父/子上下文:

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

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