在iOS应用程序中,我想使用一个既有NSIncrementalStore子类的NSPersistentStoreCoordinator,用于从REST API获取数据,也有用于保存到磁盘的SQLite存储。但是,如果我将这两种类型的持久性存储都添加到我的协调程序中,那么在我的托管对象上下文上调用save:就不会有任何效果。如果我只添加了一个持久存储,而不是我的NSIcrementalStore子类的类型,那么保存就会按预期工作。
有什么方法可以实现这个功能吗?
发布于 2012-09-08 09:05:02
根据我的经验,最好的解决方案是拥有多个托管对象上下文,每个上下文都有自己的模型。
然而,有一种方法可以实现你想要的:
// 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是如何工作的:
Core Data Programming Guide - Persistent Store Coordinator
SO: Two persistent stores for one managed object context - possible?
SO: Can two managed object context share one single persistent store coordinator?
另请查看TechZen在第二个关于配置的链接中的评论,并在此处阅读:
Core Data Programming Guide - Configurations
这里有一个很好的教程来管理两个对象上下文:
Multiple Managed Object Contexts with Core Data
https://stackoverflow.com/questions/12321954
复制相似问题