skip to content

In Core Data, how do you ship a read-only product catalogue store beside the user's own store in one NSPersistentContainer?

level: seniorimportance: nice to knowfreq 25%

answer

  1. split the model, not the container
  2. configurations in the model editor
  3. one description per store
  4. configuration name plus isReadOnly
  5. no relationships across stores

basics

~20 s

Split the entities into two model configurations, give the container one NSPersistentStoreDescription per store with its configuration name, and mark the bundled catalogue's description isReadOnly. Core Data routes each fetch and save to the store whose configuration holds the entity.

solid answer

~40 s

In the model editor add two configurations, `Catalogue` with `Product` and `PriceList`, and `User` with `Customer`, `Order` and `Visit`. Set `persistentStoreDescriptions` to two descriptions: one whose `url` is the catalogue file shipped in the bundle, with `configuration = "Catalogue"` and `isReadOnly = true`, and one in the app's directory with `configuration = "User"`. `loadPersistentStores` then calls its completion once per store, and one `viewContext` reads both, because the coordinator presents its stores as one aggregate and sends each entity to the store whose configuration contains it. Two limits follow: a relationship between objects in different stores fails to save, so an order refers to a product by an identifier or a fetched property; and a new catalogue object has no writable store, so its save fails.

code

swift · 24 lines
swift
import CoreData

func makeFieldSalesContainer() -> NSPersistentContainer {
    let container = NSPersistentContainer(name: "FieldSales")

    // Shipped in the app bundle, built with journal_mode=DELETE so it is one file.
    guard let catalogueURL = Bundle.main.url(forResource: "Catalogue", withExtension: "sqlite") else {
        fatalError("Catalogue.sqlite missing from the bundle")
    }
    let catalogue = NSPersistentStoreDescription(url: catalogueURL)
    catalogue.configuration = "Catalogue"   // Product, PriceList
    catalogue.isReadOnly = true

    let userURL = NSPersistentContainer.defaultDirectoryURL().appendingPathComponent("User.sqlite")
    let user = NSPersistentStoreDescription(url: userURL)
    user.configuration = "User"             // Customer, Order, Visit

    container.persistentStoreDescriptions = [catalogue, user]
    container.loadPersistentStores { description, error in
        // Runs twice: once per description.
        if let error { fatalError("\(description.configuration ?? "store") failed: \(error)") }
    }
    return container
}

go deeper

for a junior

Know that one container can load several stores, one description each, and that a configuration names which entities a store holds.

for a middle

Build the two descriptions with configuration and isReadOnly, and explain how the coordinator routes each entity to its store.

for a senior

Spot the limits before they ship: no cross-store relationships, a failing save for catalogue inserts, and a WAL-mode seed that can't open from a read-only folder.

for a principal

Weigh the split's payoff, a catalogue replaced every release with no user-data migration, against the identifier links and two-file setup the team then maintains.

## Configurations split one model into stores A **configuration** is a named subset of a managed object model's entities. In Xcode's model editor you add a configuration and assign entities to it; in code, `setEntities(_:forConfigurationName:)` does the same, and `configurations` and `entities(forConfigurationName:)` read them back. A store description's `configuration` property names the subset that store holds. Apple's documentation adds one rule: the configuration can be `nil`, meaning the whole model, but then no other configurations are allowed. For the field-sales app the split is: - **Catalogue**: `Product` and `PriceList`, written by a build step and shipped in the app bundle. - **User**: `Customer`, `Order` and `Visit`, created on the device and saved as the rep works. ## Building the two descriptions 1. Create the container as usual with `NSPersistentContainer(name: "FieldSales")`. 2. Make a description for the catalogue file's URL, set `configuration = "Catalogue"` and `isReadOnly = true`. `isReadOnly` is a convenience for `NSReadOnlyPersistentStoreOption`. 3. Make a description for `User.sqlite` in `defaultDirectoryURL()` (or the app group folder) with `configuration = "User"`. 4. Assign both to `persistentStoreDescriptions` and call `loadPersistentStores`; the completion runs twice, once per description. After that one `viewContext` works across both stores. Fetch `Product` and the coordinator reads the catalogue; insert an `Order` and the save writes `User.sqlite`. Apple's two-store sample describes the same behaviour: Core Data routes each request to the right store based on where the entities are. ## Shipping the catalogue in the bundle Core Data creates SQLite stores in WAL journal mode, so a seed built the default way consists of a `.sqlite` file plus `-wal` and `-shm` files. A WAL-mode store in a folder Core Data cannot write to can fail to load with SQLite error 14, "unable to open database file", even with `isReadOnly` set. Two ways around it: - Build the seed in rollback-journal mode, so it is one self-contained file that opens read-only from a folder Core Data can't write to, such as the app bundle: ```swift import CoreData // Build step that writes the catalogue seed as a single file. func makeSeedDescription(at seedURL: URL) -> NSPersistentStoreDescription { let seed = NSPersistentStoreDescription(url: seedURL) seed.configuration = "Catalogue" seed.setValue("DELETE" as NSString, forPragmaNamed: "journal_mode") return seed } ``` - Or copy the seed to a writable directory at first launch, replacing it when a release ships a newer catalogue, and still open it with `isReadOnly` so the app can't modify it. Either way a catalogue update ships as a new file, and the user's store is untouched. ## What the split allows and refuses | Operation | Result | |---|---| | Fetch `Product` | Served from the catalogue store | | Insert and save an `Order` | Written to the user store | | Insert and save a `Product` | Fails with Cocoa error 134020 (`NSPersistentStoreIncompatibleSchemaError`): no writable store holds that entity | | Save an `Order` whose relationship points at a `Product` | Fails with the same error; relationships can't join objects in two stores | | A fetched property from `Product` to orders | Works, but isn't updated on save and can't be used in a fetch predicate | So cross-store links are modelled differently: - Store the product's stable identifier (its SKU) on the `Order` and fetch the `Product` by it. - Or add a **fetched property** whose predicate matches that identifier, and call `refresh(_:mergeChanges:)` on the object to re-run it after changes. ## Why split at all - The catalogue can be replaced every release without a migration of the user's data. - `isReadOnly` turns an accidental write into an error rather than a silent edit of reference data. - The user's store stays small, and only it needs persistent history or syncing; Apple's two-store sample mentions mirroring just one store to CloudKit for this reason. ## Working with two stores day to day - A fetch request can be limited to particular stores through `affectedStores`, inherited from `NSPersistentStoreRequest`; without it the coordinator searches every store that holds the entity. - Persistent history requests go to every store too, so when only the user store tracks history, scope them to it with `affectedStores`. - Each store object reports its `configurationName`, which is how code finds the user store among `persistentStores`. Which data deserves a store at all, and how the catalogue reaches the device, are decisions for the system design material on local storage.

  • How does an Order refer to a Product when they live in different stores?
    Store the product's stable identifier, such as its SKU, on the Order and fetch the Product by it, or add a fetched property whose predicate matches that identifier. A fetched property can't be used in a fetch predicate and isn't updated on save; refresh the object with refresh(_:mergeChanges:) to re-run it.
  • Why might the bundled catalogue fail to load even with isReadOnly set?
    A seed built in the default WAL mode comes with -wal and -shm files, and a WAL store in a folder Core Data can't write to can fail with SQLite error 14, 'unable to open database file'. Build the seed with journal_mode set to DELETE so it is one file, or copy it to a writable folder first.
  • What error appears when the app inserts a Product into this setup and saves?
    The save fails with Cocoa error 134020, NSPersistentStoreIncompatibleSchemaError, and a message about an incompatible model configuration, because no writable store holds Product. Roll back the insert; catalogue changes ship as a new catalogue file.

  • Each store needs its own NSPersistentContainer and its own viewContext.
  • A relationship from Order to Product works across the two stores.
  • Every fetch has to name the store it should read from.
  • isReadOnly blocks deletes but still lets Core Data insert into the store.
  • A bundled WAL-mode seed always opens fine once isReadOnly is set.