<!--
{
  "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/View/modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)",
  "metadataVersion" : "0.1.0",
  "role" : "Instance Method",
  "symbol" : {
    "kind" : "Instance Method",
    "modules" : [
      "SwiftUI",
      "SwiftUI"
    ],
    "preciseIdentifier" : "s:7SwiftUI4ViewP01_a5Data_aB0E14modelContainer3for8inMemory17isAutosaveEnabled0j4UndoL07onSetupQr0aD015PersistentModel_pXp_S3bys6ResultOyAK0qF0Cs5Error_pGctF::OverloadGroup"
  },
  "title" : "modelContainer(for:inMemory:isAutosaveEnabled:isUndoEnabled:onSetup:)"
}
-->

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

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

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

## Parameters

`modelType`

The model type 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 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, the `RecipesList` view sets a model container to use
for all of its contents, configured to store instances of `Recipe`:

```
@Model class Recipe { ... }
...
RecipesList()
    .modelContainer(for: Recipe.self)
```

The environment’s [`modelContext`](/documentation/SwiftUI/EnvironmentValues/modelContext) property will be
assigned a new context associated with this container. All implicit
model context operations in this view, 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 `modelType` 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)