在iOS应用程序,我想用一个NSPersistentStoreCoordinator既与NSIncrementalStore子类,从一个REST API获取数据,而且还和SQLite存储,保存到磁盘.但是,如果我将两种类型的持久存储添加到协调器,则调用save:我的托管对象上下文不起作用.如果我只添加一个持久存储,而不是我的NSIcrementalStore子类的类型,那么保存按预期工作.
有没有办法实现这个功能?
小智 10
根据我的经验,最好的解决方案是拥有多个托管对象上下文,每个上下文都有自己的模型.
但是,有一种方法可以实现您的目标:
// 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的工作原理:
另请查看TechZen在第二个链接中关于配置的评论,并在此处阅读:
这是一个管理两个对象上下文的好教程:
| 归档时间: | 
 | 
| 查看次数: | 2984 次 | 
| 最近记录: |