首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用两种类型的持久存储的NSPersistentStoreCoordinator?

使用两种类型的持久存储的NSPersistentStoreCoordinator?
EN

Stack Overflow用户
提问于 2012-09-08 00:23:53
回答 1查看 3.1K关注 0票数 10

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

有什么方法可以实现这个功能吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2012-09-08 09:05:02

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

然而,有一种方法可以实现你想要的:

代码语言:javascript
复制
// 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

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12321954

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档