Containers are references. The correct way to achieve this I think would be by using AppDependencyManager. Here is a working example:
@Model
final class Test: @unchecked Sendable {
var text: String
init(text: String) {
self.text = text
}
}
struct InsertTestIntent: AppIntent {
static var title: LocalizedStringResource = "Insert model"
static var openAppWhenRun: Bool = true
static var isDiscoverable: Bool = false
@Parameter(title: "Text")
var text: String
@Dependency
private var modelContainer: ModelContainer
init(text: String) {
self.text = text
}
init() {}
@MainActor
func perform() async throws -> some IntentResult {
modelContainer.mainContext.insert(Test(text: text))
return .result()
}
}
struct ContentView: View {
@Query
private var items: [Test]
@State
private var text = ""
var body: some View {
NavigationStack {
List {
TextField("Text", text: $text)
Button("Insert model", intent: InsertTestIntent(text: text))
Section {
ForEach(items) { item in
Text(item.text)
}
}
}
.navigationTitle("Home")
}
}
}
Topic:
App & System Services
SubTopic:
General
Tags: