<!--
{
  "availability" : [
    "iOS: 17.0.0 -",
    "iPadOS: 17.0.0 -",
    "macOS: 14.0.0 -",
    "tvOS: 17.0.0 -",
    "watchOS: 10.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "SwiftUI",
  "identifier" : "/documentation/SwiftUI/Scene/modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)-2ake3",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI",
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI5SceneP01_a5Data_aB0E14modelContainer3for8inMemory17isAutosaveEnabled0j4UndoL07onSetupQrSay0aD015PersistentModel_pXpG_S3bys6ResultOyAK0qF0Cs5Error_pGctF"
  },
  "title" : "modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)"
}
-->

# modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)

Sets the model container in this scene for storing the provided
model types, creating a new container if necessary, and also sets a
model context for that container in this scene’s environment.

```
@MainActor @preconcurrency func modelContainer(for modelTypes: [any PersistentModel.Type], inMemory: Bool = false, isAutosaveEnabled: Bool = true, isUndoEnabled: Bool = false, onSetup: @escaping (Result<ModelContainer, any Error>) -> Void = { _ in }) -> some Scene
```

## Parameters

`modelTypes`

The model types defining the schema used to create the
model container.

`inMemory`

Whether the container should store data only in memory.

`isAutosaveEnabled`

`true` if autosave is enabled.

`isUndoEnabled`

use `undoManager` in the scene’s environment to
manage undo operations for the model container.

`onSetup`

A callback that will be invoked when the creation of the
container has has succeeded or failed.

## Discussion

In this example, `RecipesApp` sets a shared model container to use for
all of its windows, configured to store instances of `Recipe` and
`Ingredient`:

```
@Model class Recipe { ... }
@Model class Ingredient { ... }

@main
struct RecipesApp: App {
    var body: some Scene {
        WindowGroup {
            RecipesList()
        }
        .modelContainer(for: [Recipe.self, Ingredient.self])
    }
}
```

The environment’s `EnvironmentValues/modelContext` property will be
assigned a new context associated with this container. All implicit
model context operations in this scene, such as `Query`
properties, will use the environment’s context.

By default, the container stores its model data persistently on disk.
To only store data in memory for the lifetime of the app’s process, pass
`true` to the `inMemory:` parameter.

The container will only be created once. New values that are passed to
the `modelTypes` and `inMemory` parameters after the view is first
created will be ignored.

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)