skip to content

Your SwiftData field-inspection app imports 10,000 records from a server while the list stays on screen; why use a @ModelActor rather than mainContext, and how do you build it?

level: seniorimportance: must knowfreq 58%

answer

  1. mainContext is main-actor work
  2. macro turns an actor into a model actor
  3. its own context on the same container
  4. no autosave: save in batches
  5. send values in, not models

basics

~20 s

mainContext is @MainActor, so 10,000 inserts and saves on it compete with the UI. A @ModelActor owns its own ModelContext on the same container; pass it the container and Sendable records, insert there and save in batches.

solid answer

~40 s

The container's `mainContext` is declared `@MainActor`, so an import through it runs every insert and save on the main actor while the user scrolls. Instead, declare an `actor` with the `@ModelActor` macro. The macro generates `modelContainer`, `modelExecutor` and an `init(modelContainer:)` that creates a new `ModelContext` on that container and wraps it in a `DefaultSerialModelExecutor`, so the actor's `modelContext` is used only from the actor. Create it with the container, which is `Sendable`, and send it the downloaded data as `Sendable` value types, not model objects. That context's `autosaveEnabled` starts at the documented default, `false`, so call `save()` every few hundred or thousand inserts and at the end; unsaved inserts never reach the store. Once saved, fetches from other contexts, including the main one, read the new rows.

code

swift · 35 lines
swift
import SwiftData
import Foundation

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

struct InspectionRecord: Sendable {
    let remoteID: Int
    let siteName: String
}

@ModelActor
actor InspectionImporter {
    func importRecords(_ records: [InspectionRecord]) throws {
        for (index, record) in records.enumerated() {
            modelContext.insert(Inspection(remoteID: record.remoteID, siteName: record.siteName))
            if index % 1_000 == 999 {
                try modelContext.save()   // this context does not autosave
            }
        }
        try modelContext.save()
    }
}

@MainActor
func startImport(container: ModelContainer, records: [InspectionRecord]) async throws {
    let importer = InspectionImporter(modelContainer: container)
    try await importer.importRecords(records)
}

go deeper

for a junior

Know that long imports should not run on the main context, and that SwiftData offers @ModelActor for work elsewhere.

for a middle

Explain what @ModelActor generates: its own context on the shared container, created in init(modelContainer:), used only from the actor.

for a senior

Design the importer: Sendable records in, batched saves because the context does not autosave, idempotent retries, and values rather than models out.

for a principal

Weigh batch size against memory and change churn, and decide how imports report progress and recover after a crash across the app.

## Why not the main context `ModelContainer.mainContext` is declared `@MainActor`. Any code that uses it runs on the main actor, the same one that runs SwiftUI views. Creating 10,000 `Inspection` models, inserting them and saving is real work, and doing it there competes with scrolling and animations. Wrapping the loop in `Task { }` from a view does not help, because that task inherits the main actor. You also cannot simply create a context on the main actor and hand it to a background task: SwiftData marks `ModelContext`'s `Sendable` conformance unavailable with the message "contexts cannot be shared across concurrency contexts". A context must be created and used inside one isolation domain. `@ModelActor` gives it one. ## What @ModelActor generates `@ModelActor` is an attached macro that, in Apple's words, "converts a Swift actor into a model actor by generating boilerplate code". Expanded, it adds: - `nonisolated let modelContainer: ModelContainer` - `nonisolated let modelExecutor: any ModelExecutor` - `init(modelContainer:)`, which creates `ModelContext(modelContainer)` and wraps it in `DefaultSerialModelExecutor(modelContext:)` - conformance to the `ModelActor` protocol, whose extension supplies `modelContext` (isolated to the actor), the actor's `unownedExecutor`, and a `self[id, as:]` subscript for loading a model by identifier The result is an actor with its own context on the **same container** as the UI, so both read and write the same store. ## Building the importer 1. **Decode off the model layer.** Turn the server response into `Sendable` value types (`struct InspectionRecord: Sendable`). Model objects are not `Sendable`, so they cannot be what you send in. 2. **Create the actor with the container.** `ModelContainer` is declared `Sendable`, so `InspectionImporter(modelContainer: container)` is legal from the main actor. 3. **Insert inside the actor.** Build each `Inspection` from a record and call `modelContext.insert(_:)`. 4. **Save in batches.** The actor's context starts with `autosaveEnabled` at its documented default, `false`, so nothing reaches the store until you call `save()`. Saving every 500 or 1,000 inserts bounds how much unsaved work a failure can lose and lets the list show progress; one save at the end is required either way. 5. **Report back with values.** Return a count, or identifiers, never the models themselves. ## Calling it from the UI The screen that starts the import creates the importer with the shared container and awaits its method from a task. While the import runs, the actor's context holds only the current batch's pending inserts, and the UI keeps working against the main context. For a cancellable import, check `Task.isCancelled` between batches, save what is complete and return; the saved batches stay in the store, which is one more reason the import must be safe to re-run. ## How the list sees the new rows The container performs the write when the actor's context saves. From then on the rows are in the store, and fetches made by other contexts, including the main context, read them. The `ModelContext.didSave` notification lists the inserted identifiers if code needs to react to a specific save. How a SwiftUI query refreshes is covered with querying and fetching. ## Judgment calls and traps | Choice | Trade-off | |---|---| | Batch size small | More saves and more change notifications, less unsaved work at risk | | Batch size large | Fewer saves, but more unsaved work at risk and a longer pause per save | | One importer per import | A fresh context each time; nothing carries over between imports | | One long-lived importer | Calls run one at a time on the actor, so imports cannot overlap | - Apple's documentation does not say which thread a model executor uses. Do not promise "background thread" in a design doc; measure with Instruments that the main actor stays free. - A crash halfway leaves the saved batches in the store. Make the import idempotent, for example by matching the server's own identifier, so a retry does not duplicate rows. - Errors from `save()` propagate out of the actor method; handle them where the import was started. Passing a model across the actor boundary by identifier is its own topic, as are the actor and `Sendable` rules of the Swift language.

  • Why not create a ModelContext on the main actor and pass it to Task.detached for the import?
    SwiftData declares `ModelContext`'s `Sendable` conformance unavailable with the message "contexts cannot be shared across concurrency contexts", and Swift 6 language mode rejects sending a main-actor value into a detached task. Create the context where it is used; `@ModelActor` does that in its generated initializer.
  • The import crashes after six of ten batches. What is in the store, and how should a retry behave?
    The six saved batches are in the store; the unsaved seventh is lost with the context. A retry should skip or update records already imported, for example by matching the server's identifier stored on each model, instead of inserting duplicates.
  • How do you check that the import really leaves the main actor free?
    Measure rather than assume: Apple's documentation does not specify which thread a model executor runs on. Profile the import with Instruments, watch for main-thread hangs while scrolling, and keep the caller from awaiting the import on a path that blocks the UI.

  • A @ModelActor's context autosaves just like mainContext.
  • Wrapping the import in Task { } inside a view moves it off the main actor.
  • Pass the main context into the actor so both share one context.
  • @ModelActor guarantees its work runs on a background thread.
  • Return the imported model objects to the UI when the import finishes.