0

I have a requirement for two different CoreData database stores, depending on which mode my application is running in. It will only need to be switched when the application first runs.

Ideally this would get setup with the persistentContainer:

lazy var persistentContainer: NSPersistentContainer = 
{
    let container = NSPersistentContainer(name: "myApp")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? 
        {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
}

I basically just need to find a command like:

if mode == 1
{
    storeName = "MyStore1.sqlite"
}
else
{
    storeName = "MyStore2.sqlite"
}
container.useStore(storeName)
iphaaw
  • 6,764
  • 11
  • 58
  • 83

2 Answers2

1

You're on the right track. In broad strokes, a typical configuration would include a single NSManagedObjectContext, which requires a NSPersistentStoreCoordinator, which in turn requires a NSManagedObjectModel. The context can have another context above it, if you wish to have an intermediate step between your front end and the persistent store.

Either way, you have a couple options (and probably more):

  1. Add another store to your NSPersistentStoreCoordinator (see this answer)
  2. If you also want two separate models for each store, create two different instances of NSManagedObjectContext, each with its own NSPersistentStoreCoordinator and NSManagedObjectModel.

Option #2 would be a bit clunky to manage in code so if you only worry about where the data is physically stored, I'd go with option #1. Otherwise, you may want to create some kind of a context manager that will correctly oversee each context (you can also put your mode == 1 / model == 2 logic here) to make sure they don't step on each other's toes.

olx
  • 71
  • 4
1

When you initialise a persistent container with init(name:), the name is used to locate both the model and the persistent store. From the docs:

By default, the provided name value is used to name the persistent store and is used to look up the name of the NSManagedObjectModel object to be used with the NSPersistentContainer object.

But there is another initialiser you can use, init(name:, managedObjectModel:), which will allow you to specify separate names for the model and the store. From the docs:

By default, the provided name value of the container is used as the name of the persisent store associated with the container. Passing in the NSManagedObjectModel object overrides the lookup of the model by the provided name value.

So you can achieve what you want just by specifying the correct name and managedObjectModel parameters when you initialise the persistent container.

pbasdf
  • 21,386
  • 4
  • 43
  • 75