skip to content

In SwiftData, how do you configure a ModelContainer with ModelConfiguration for an in-memory store, a custom file location or a read-only store?

level: middleimportance: should knowfreq 45%

answer

  1. pass configurations to the container
  2. memory, URL or read-only
  3. default built from entitlements
  4. name and schema per store
  5. the URL initializer has no memory flag

basics

~10 s

Pass ModelConfiguration values to ModelContainer(for:configurations:). isStoredInMemoryOnly: true keeps the store in memory, the url: initializer places the file, and allowsSave: false makes it read-only; with none, SwiftData builds a default configuration.

solid answer

~40 s

A `ModelConfiguration` describes one store and the container takes one or more of them. `ModelConfiguration(isStoredInMemoryOnly: true)` gives an ephemeral store that never touches the file system, which is what unit tests want. `ModelConfiguration(_:schema:url:allowsSave:cloudKitDatabase:)` puts the store at a file URL you choose, and `allowsSave: false` makes a store read-only, for example a seed database shipped in the bundle. The `name` and `schema` parameters let one container hold several stores, each holding a subset of the models. If you pass no configuration, SwiftData builds a default one from your app's entitlements and the type's defaults. The container initializers throw, so handle the error instead of assuming the store opened.

code

swift · 21 lines
swift
import SwiftData
import Foundation

@Model final class Inspection {
    var siteName: String
    var inspectedAt: Date
    init(siteName: String, inspectedAt: Date) {
        self.siteName = siteName
        self.inspectedAt = inspectedAt
    }
}

func makeContainer(inMemory: Bool) throws -> ModelContainer {
    let configuration = ModelConfiguration(isStoredInMemoryOnly: inMemory)
    return try ModelContainer(for: Inspection.self, configurations: configuration)
}

func makeSeedContainer(seedURL: URL) throws -> ModelContainer {
    let seed = ModelConfiguration("Seed", url: seedURL, allowsSave: false)
    return try ModelContainer(for: Inspection.self, configurations: seed)
}

go deeper

for a junior

Know that a container can be built in memory for tests and that ModelConfiguration is where you say so.

for a middle

Explain the configuration initializers and parameters: isStoredInMemoryOnly, url, allowsSave, name and schema, and what SwiftData does when you pass no configuration.

for a senior

Show how you isolate tests with a fresh in-memory container, split stores by schema, and handle a container initializer that throws instead of crashing at launch.

for a principal

Discuss which data deserves its own store, such as read-only reference data or app-group data shared with extensions, and what each extra store costs to migrate.

## What a configuration is A `ModelContainer` always has at least one **configuration**: a `ModelConfiguration` value describing one store, meaning where it lives, which models it holds and whether it can be written. You pass configurations to the container's initializer: ```swift let configuration = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: Inspection.self, configurations: configuration) ``` If you pass none, Apple's documentation says the framework creates one for you "by combining your app's entitlements with the type's default values". A configuration created without an explicit name is named `"default"`. ## The initializers and their parameters | Initializer | Use it for | |---|---| | `init(isStoredInMemoryOnly:)` | The quickest in-memory or default store | | `init(for:isStoredInMemoryOnly:)` | A store limited to the listed model types | | `init(_:schema:isStoredInMemoryOnly:allowsSave:groupContainer:cloudKitDatabase:)` | A named store, optionally in an app group | | `init(_:schema:url:allowsSave:cloudKitDatabase:)` | A store at a file URL you choose | The parameters that matter for this question: - **`isStoredInMemoryOnly`** (default `false`): when `true` the store exists only in memory. Nothing is written to disk, and the data disappears with the container. - **`url`**: the location of the store file. Note that the URL initializer has **no** `isStoredInMemoryOnly` parameter; a store you place at a URL is on disk by definition. - **`allowsSave`** (default `true`): `false` makes the store read-only, which suits a reference database copied into the bundle. - **`name`** and **`schema`**: identify a store and limit it to some of your model types, so one container can hold several stores. - **`groupContainer`** (default `.automatic`): with `.identifier(_:)` you place the store in an app group that a widget or extension can also open. `cloudKitDatabase` also defaults to `.automatic`, so an app with CloudKit entitlements syncs its default store; `.none` keeps a store local. Sync itself is covered with CloudKit. ## In-memory stores for tests The most common reason to touch a configuration is testing. A test that uses the default configuration writes to the same on-disk store every run, so rows left by one test leak into the next. The fix is to build a fresh container per test: 1. Create `ModelConfiguration(isStoredInMemoryOnly: true)`. 2. Create a `ModelContainer` with the model types under test and that configuration. 3. Use its context, assert, and let the container go away at the end of the test. Each container gets its own empty store, so tests stay isolated and fast. Sample-data containers for SwiftUI previews follow the same idea and are covered with SwiftData's SwiftUI integration. ## Choosing a configuration Match the configuration to the job the store does: 1. **The app's own data:** pass nothing, or a named configuration, and let SwiftData place the store; this is what most apps ship. 2. **Unit tests:** `isStoredInMemoryOnly: true`, one container per test. 3. **A bundled reference database:** the `url:` initializer pointing at the bundled file, with `allowsSave: false`, because the app bundle is not a place to write. 4. **Data a widget or extension also reads:** a `groupContainer` set to `.identifier(_:)` with the app group both targets share. Each choice is a value you can see in code review, which is the point: the store's location and mutability are explicit rather than implied. ## Several stores in one container Give each configuration a `name` and a `schema` listing only its models, then pass all of them to `ModelContainer(for:migrationPlan:configurations:)`. A common split is user data in one store and a read-only reference catalogue in another. ## Failure and mistakes - Every `ModelContainer` initializer **throws**. Opening a store can fail, for example when a migration fails; crashing with `try!` turns that into a launch crash, so decide what the app does instead. - `allowsSave: false` means a read-only store, not "saving later". - An in-memory container that is recreated loses everything; keep one instance for as long as the data must live. - A configuration's `id` is its store `url`, so give each store its own file. Passing a migration plan to the container is covered with schema migrations.

  • Why might SwiftData-backed unit tests pass alone but fail when run together?
    They probably share the default on-disk store, so rows inserted by one test are fetched by another. Build a new `ModelContainer` per test with `ModelConfiguration(isStoredInMemoryOnly: true)`; each container starts empty and vanishes with the test.
  • How would you keep a shipped reference catalogue separate from user data in one SwiftData container?
    Use two configurations: one named store whose `schema` lists the catalogue models, opened from a bundle URL with `allowsSave: false`, and one for user models. Pass both to the container; each model type lives in the store whose schema includes it.

  • Every ModelContainer needs an explicit ModelConfiguration or it throws.
  • allowsSave: false defers saving until the app goes to the background.
  • You can combine url: and isStoredInMemoryOnly: in one ModelConfiguration initializer.
  • Unit tests can safely share the app's default on-disk store.
  • Creating a ModelContainer cannot fail, so try! is always safe.