Found this thread wile trying to solve a similar problem, and silence all the errors from console.
This isn't an elegant solution, and may not apply directly but it is what worked for me so I wanted to share – to get updates in a view. Instead of "updating" the context I delete the existing and then re-add it.
@MainActor
func load_video_in_background(context: ModelContext) async throws {
let existing = try context.fetch(FetchDescriptor<Video>(
predicate: #Predicate { $0.id == content_id }
)).first
// async fetch from db here to get fresh data
// ...
// transform fetched data to class & validate
// ...
if let existing = existing {
context.delete(existing)
}
context.insert(content)
}
Then in my view I pass the context into this function
@Environment(\.modelContext) private var context
// view logic
// ...
.task {
do {
try await load_video_in_background(context: context)
}
}
So far I haven't had any problems with the above, obviously make sure you are relying on @Query and instead of @Binding or @State to show your data.
Topic:
App & System Services
SubTopic:
iCloud & Data
Tags: