NSPersistentStoreCoordinator有两种类型的持久存储? [英] NSPersistentStoreCoordinator with two types of persistent stores?
问题描述
在iOS应用程式中,我想使用 NSIncrementalStore
子类别的 NSPersistentStoreCoordinator
从REST API,还可以用SQLite存储,保存到磁盘。如果我将两种类型的持久性存储添加到我的协调器,但是在我的受管对象上下文中调用 save:
没有效果。如果我只添加一个持久存储,而不是我的 NSIcrementalStore
子类的类型,那么保存工作原意。
In an iOS app, I would like to use an NSPersistentStoreCoordinator
with both an NSIncrementalStore
subclass, for fetching data from a REST API, but also with an SQLite store, to save to disk. If I add both types of persistent stores to my coordinator, however, calling save:
on my managed object context has no effect. If I only add the one persistent store, not of the type for my NSIcrementalStore
subclass, then the save works as intended.
有什么方法可以实现这个功能吗?
Is there any way to achieve this functionality?
推荐答案
我的经验中最好的解决方案是有多个管理对象上下文,每个都有自己的模型。
The best solution in my experience is to have multiple managed object contexts, each having its own model.
但是,有一种方法可以完成你想要的:
However, there is a way to accomplish what you want:
// 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工程:
You should also check these links to get a better idea about how Core Data works:
SO: Two persistent stores for one managed object context - possible?
同时检查注释由TechZen在第二个链接关于配置和阅读它在这里:
Also check the comment by TechZen in the second link about configurations and read about it in here:
这里是一个很好的教程来管理两个对象上下文:
and here is a nice tutorial to manage two object contexts:
这篇关于NSPersistentStoreCoordinator有两种类型的持久存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!