NSPersistentStoreCoordinator with two types of persistent stores?

前端 未结 1 1346
青春惊慌失措
青春惊慌失措 2021-02-08 13:19

In an iOS app, I would like to use an NSPersistentStoreCoordinator with both an NSIncrementalStore subclass, for fetching data from a REST API, but als

相关标签:
1条回答
  • 2021-02-08 14:15

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

    You should also check these links to get a better idea about how Core Data works:

    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?

    Also check the comment by TechZen in the second link about configurations and read about it in here:

    Core Data Programming Guide - Configurations

    and here is a nice tutorial to manage two object contexts:

    Multiple Managed Object Contexts with Core Data

    0 讨论(0)
提交回复
热议问题