El contenedor y el contexto del modelo
Configure el almacenamiento con modelContainer.
El contenedor y el contexto del modelo es una lección gratuita de SwiftUI Academy en CoddyKit. Esta es la lección 2 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de SwiftUI Academy, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de SwiftUI Academy incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
What a Container Is
The model container is the engine that sets up your storage on disk. Your whole app shares one container for all its SwiftData models.
Adding the Container
Attach a container to your app with the modelContainer modifier on a scene. One line gives every view access to your saved data.
WindowGroup {
ContentView()
}
.modelContainer(for: Task.self)Listing Multiple Models
Pass an array to register several models at once. The container then knows about every type your app needs to save.
.modelContainer(for: [Task.self, Project.self])What a Context Is
The model context is your working space for changes. You insert, edit, and delete through it, then it saves to the container.
Reading the Context
Grab the active context inside a view with the @Environment property wrapper. SwiftData injects it for you automatically.
@Environment(\.modelContext) private var contextInserting an Object
Call insert on the context to start tracking a new object. From this point SwiftData watches it for saving.
context.insert(Task(title: "Buy milk"))Automatic Saving
SwiftData usually autosaves changes for you at smart moments. You rarely need to save by hand in a simple app.
Saving Manually
When you need certainty, call save on the context to write changes right now. It is handy before a critical step.
try context.save()In-Memory Containers
Set isStoredInMemoryOnly to true for a throwaway store. It is perfect for previews and tests that should not touch the disk.
let config = ModelConfiguration(
isStoredInMemoryOnly: true)Custom Configuration
A ModelConfiguration lets you tune where and how data is stored. You pass it when building a container by hand.
let container = try ModelContainer(
for: Task.self, configurations: config)One Container, Many Views
Because the container lives at the app level, every view shares the same data. Edits in one screen show up everywhere instantly.
Quick Check
Quick check on container and context.
Recap: Container & Context
You set up storage with modelContainer, then insert and save through the context from @Environment. Your app can now read and write data. ✅
Preguntas frecuentes
¿La lección «El contenedor y el contexto del modelo» es gratis?
Sí — el texto completo de «El contenedor y el contexto del modelo» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de SwiftUI Academy, actualiza a CoddyKit PRO. El curso de SwiftUI Academy incluye 4 lecciones en total.
¿Qué aprenderé en «El contenedor y el contexto del modelo»?
Configure el almacenamiento con modelContainer. Practicas SwiftUI Academy con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar SwiftUI Academy?
No se requiere experiencia previa. SwiftUI Academy en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 2 de 4.
¿Cuánto tiempo toma la lección «El contenedor y el contexto del modelo»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de SwiftUI Academy?
Sí. Cada lección de SwiftUI Academy incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- Definir tipos @Model
- El contenedor y el contexto del modelo
- Consultar con @Query
- Insertar, actualizar y eliminar