Using SwiftData outside of SwiftUI – Swift-data

by
Ali Hasan
swift-data xcode15

Quick Fix: Create a model container once and store it in a stable location like UIApplicationDelegate, a Singleton, or a service, and access the context directly from the container.

The Problem:

In a Swift user interface application, outside of a view controller, how to obtain the model container and context to CRUD objects using the SwiftData library? Specifically, what code is equivalent to let context = self.newSwiftContext(from: Trip.self), as shown in the WWDC video?

The Solutions:

Solution 1: Creating a Model Container and Accessing Context Outside SwiftUI

  1. Create a Model Configuration:

    • Define a model configuration to specify the behavior of the data model. In this example, the configuration is set to store the model in memory only, without allowing saves.
      let configuration = ModelConfiguration(isStoredInMemoryOnly: true, allowsSave: false)
      
  2. Create the Model Container:

    • Use the ModelContainer initializer to create a container for the specified model types. Here, the container is for the Trip and Accommodation types.
      let container = try ModelContainer(for: Trip.self, Accommodation.self, configurations: configuration)
      
  3. Access the Main Context:

    • Access the main context directly from the container. This context can be used to perform operations on the model, such as fetching, saving, and deleting data.
      let context = container.mainContext
      
  4. Store the Container in a Stable Location:

    • It is recommended to store the container in a stable location, such as in the application delegate, a singleton, or a service that persists throughout the app’s lifetime. This ensures that the context remains accessible throughout the app’s execution.

Advantages:

  • This approach provides a way to access and manipulate data outside of a SwiftUI view.
  • It follows the recommended practice of using a model container to manage the data model.
  • The approach allows you to specify custom configurations for the model, such as storing data in memory only.

Q&A

Outside of SwiftUI, how can I get the SwiftData model context?

Create the container and access the context directly from it.

What should I do with the container?

Store it somewhere stable, like AppDelegate, a Singleton, or a preserved service.

Does SwiftData support saving?

SwiftData does not support saving, but you can use CoreData with it.

Video Explanation:

The following video, titled "SwiftData For Beginners: How To Build A To-Do List App In SwiftUI ...", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

SwiftUI Build A To-Do List App using SwiftData (Swift Data Tutorials) ... - How to Fetch Data in SwiftData using Query in SwiftUI 11:33 - How ...