【问题标题】:NSPersistentStoreCoordinator with two types of persistent stores?NSPersistentStoreCoordinator 有两种类型的持久存储?
【发布时间】:2012-09-07 16:23:53
【问题描述】:

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

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

【问题讨论】:

    标签: ios core-data


    【解决方案1】:

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

    但是,有一种方法可以实现您想要的:

    // 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

    【讨论】:

    • 谢谢,感谢这些资源,我已经正确设置了所有内容。但是,仍然存在一个问题:我有多个托管对象上下文,但是一个具有两个持久存储的持久存储协调器。当我在我的主要托管对象上下文上执行获取请求时,我只希望它与我的 SQLite 持久存储相关联,而不是使用我的 NSIncrementalStore 子类。我如何做到这一点?
    • 好像是-[NSFetchRequest setAffectedStores:]
    • @JordanKay 不客气。抱歉,我之前没有回答你关于获取请求的问题,这里阳光明媚,很热,所以我在开派对:)。但看起来你做对了! [NSFetchRequest setAffectedStores:] 是的。
    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 2013-04-08
    • 1970-01-01
    • 1970-01-01
    • 2013-03-07
    • 2016-02-04
    • 2020-05-30
    • 2012-08-18
    相关资源
    最近更新 更多