How do I access the SwiftData container from outside of SwiftUI?

123 views Asked by At

Accessing the container in SwiftUI

I'm setting up the SwiftData container in my App like this:

@main
struct MyApp: App {
    var sharedModelContainer: ModelContainer = {
        do {
            let schema = Schema([MyModel.self])
            return try ModelContainer(
                for: schema,
                configurations: ModelConfiguration(
                    schema: schema,
                    isStoredInMemoryOnly: false
                )
            )
        } catch {
            fatalError("Could not create ModelContainer: \(error)")
        }
    }()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
        .modelContainer(sharedModelContainer)
        .backgroundTask { ... }
    }
}

Accessing the container somewhere else:

I have a .backgroundTask and AppIntent that both access SwiftData.

Edit: for the .backgroundTask - as Joakim pointed out - I can simply pass-in the container:

.backgroundTask(.appRefresh("myTaskId")) {
    let container = await sharedModelContainer
    // ...
}

For the AppIntent I'm doing this:

struct MyAppIntent: AppIntent {
    // ...

    func perform() async throws -> some IntentResult {
          let schema = Schema([MyModel.self])
          let modelContainer = try ModelContainer(
              for: schema,
              configurations: ModelConfiguration(
                schema: schema,
                isStoredInMemoryOnly: false
              )
          )
           let task = Task.detached {
              let actor = MyActor(modelContainer: modelContainer)
              try await actor.doSomething()
          }
          try await task.value
          return .result()
    }
}

Is that the correct way of accessing the ModelContainer from other places?

Looking at the documentation it seems to me like it is, but maybe I'm missing something.


The issue is when I open the App after having run the Shortcut or the background task and perform something that creates a relationship for a new model that just got inserted, the App crashes and I'm getting this error:

"Unacceptable type of value for to-one relationship: property = "MyModel"; desired type = NSManagedObject; given type = NSManagedObject;

0

There are 0 answers