I'm using SwiftData and have a Siri Shortcut that inserts a new model.

When I open the App after having used the Shortcut and perform something that creates a relationship for the 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;

It sounds to me like this question is related. The problem there seems to be having two core data stacks in memory at once. Only I don't see how the CoreData solution there could be applied to SwiftData (if it even is related).

Is there any way to "kill" the context that the Shortcut used after it finished? Or any other way to fix this issue?

Here are the basic parts:

Shortcut

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()
    }
}

Actor

@ModelActor actor MyActor {
    func doSomething() {
        modelContext.insert(MyModel())
        try? modelContext.save()
    }
}

Setting up the ModelContainer inside the App

@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)
    }
}

Model

@Model MyModel {
    // v Error: "Unacceptable type of value for to-one relationship:..."
    @Relationship var someProp: OtherModel? 

    // ...
}

Adding the relationship somewhere inside the App

let someProp = OtherModel()
modelContext.insert(someProp)
myModel.someProp = someProp
try? modelContext.save()
0

There are 0 best solutions below