繁体   English   中英

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

[英]NSPersistentStoreCoordinator with two types of persistent stores?

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

有没有办法实现这个功能?

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

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

// 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:一个托管对象上下文的两个持久存储 - 可能吗?

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

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

核心数据编程指南 - 配置

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM