在后台线程中保存到CoreData上下文中

一段时间以来,我一直在为此苦苦挣扎,而苹果公司的文档和SO目前还没有帮助。 我在UIManagedDocument上使用ManagedObjectContext,下面的代码工作正常。 然后,我决定在AppDelegate中使用Apple的AppleData模板,因此在AppDelegate中创build了模型,持久性存储协调器和上下文。 获取AppDelegate的上下文没有问题,但是后台保存是一个问题。 我应该在我保存的线程上使用本地上下文,并根据苹果公司的具体情况设置相同的持久性存储协调器。 但下面的代码实际上并没有保存数据。 有人可以请指教吗? 谢谢。

- (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/

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

您的崩溃发生是因为您的NSManagedObjectContext正在使用旧的, 过时的线程约束模型来进行核心数据并发 :

secureManagedObjectContext = [[NSManagedObjectContext alloc] init];

init只是initWithConcurrencyType:一个包装initWithConcurrencyType:带有参数NSConfinementConcurrencyType 。 这使用线程约束模型创build上下文,该模型不能使用performBlock:performBlockAndWait: 只有使用较新的(不是过时的)队列约束模型的上下文可以使用这些方法,并且必须使用这些方法来访问属于它的上下文或对象。 使用队列限制和专用队列创build上下文:

secureManagedObjectContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];

如果您的代码已被迁移到使用专用队列上下文,则也可以删除串行调度队列,因为专用队列上下文提供了等效的function。