NSPersistentStoreCoordinator有两种类型的持久存储?

在iOS应用程序中,我想使用带有NSIncrementalStore子类的NSIncrementalStore ,用于从REST API获取数据,但也可以使用SQLite存储,以保存到磁盘。 但是,如果我将两种类型的持久性存储添加到协调器,则在我的托管对象上下文中调用save:无效。 如果我只添加一个持久存储,而不是我的NSIcrementalStore子类的类型,那么保存按预期工作。

有没有办法实现这个function?

根据我的经验,最好的解决方案是拥有多个托管对象上下文,每个上下文都有自己的模型。

但是,有一种方法可以实现您的目标:

 // create the store coordinator NSPersistentStoreCoordinator *storeCoordinator = [[NSPersistentStoreCoordinator alloc] init]; // create the first store NSPersistentStore *firstStore = [storeCoordinator addPersistentStoreWithType: NSIncrementalStore configuration:nil URL:urlToFirstStore options:optionsForFirstStore error:&error]; // now create the second one NSPersistentStore *secondStore = [storeCoordinator addPersistentStoreWithType:NSSQLiteStore configuration:nil URL:urlToSecondStore options:optionsForSecondStore error:&error]; // Now you have two stores and one context NSManagedObjectContext *context = [[NSManagedObjectContext alloc] init]; [context setPersistentStoreCoordinator:storeCoordinator]; // and you can assign your entities to different stores like this NSManagedObject *someObject = [[NSManagedObject alloc] initWithEntity:someEntity insertIntoManagedObjectContext:context]; // here the relevant part [context assignObject:someObject toPersistentStore:firstStore]; // or secondStore .. 

您还应该检查这些链接,以更好地了解Core Data的工作原理:

核心数据编程指南 – 持久存储协调器

SO:一个托管对象上下文的两个持久存储 – 可能吗?

SO:两个托管对象上下文可以共享一个持久存储协调器吗?

另请查看TechZen在第二个链接中关于配置的评论,并在此处阅读:

核心数据编程指南 – 配置

这是一个管理两个对象上下文的好教程:

具有核心数据的多个托管对象上下文