Facing the same issue.
Here is some code from my app for context:
In View
private func saveSocialPlatform() {
guard !socialTitle.isEmpty else { return }
let maxChars = Int(postTextMaxChars) ?? Int.max
Task {
let actor = SocialsModelActor(modelContainer: modelContext.container, mainActor: true)
do {
try await actor.saveSocial(socialTitle: socialTitle, hashtags: hashtags, maxCharsOption: maxChars, usesHashtags: usesHashtags, bestPractices: "")
withAnimation {
show = false
}
} catch {
print("Error saving a manual social platform: \(error.localizedDescription)")
}
}
}
The ModelActor
actor SocialsModelActor: ModelActor {
let modelContainer: ModelContainer
let modelExecutor: any ModelExecutor
init(modelContainer: ModelContainer) {
let context = ModelContext(modelContainer)
self.modelContainer = modelContainer
modelExecutor = DefaultSerialModelExecutor(modelContext: context)
}
func saveSocial(
socialTitle: String,
hashtags: [String],
maxCharsOption: Int,
usesHashtags: Bool,
bestPractices: String
) throws {
let newHashtags = hashtags.map { Hashtag(title: $0) }
try saveSocial(socialTitle: socialTitle, hashtags: newHashtags, maxCharsOption: maxCharsOption, usesHashtags: usesHashtags, bestPractices: bestPractices)
}
func saveSocial(
socialTitle: String,
hashtags: [Hashtag],
maxCharsOption: Int,
usesHashtags: Bool,
bestPractices: String
) throws {
try saveHashtags(hashtags: hashtags)
let newSocial = SocialsPlatform(
title: socialTitle,
hashtags: hashtags,
postTextMaxChars: maxCharsOption,
usesHashtags: usesHashtags,
bestPractices: bestPractices
)
modelContext.insert(newSocial)
try modelContext.save()
}
func saveHashtags(
hashtags: [Hashtag]
) throws {
for hashtag in hashtags {
modelContext.insert(hashtag)
}
try modelContext.save()
}
func saveHashtag(
hashtag: Hashtag
) throws {
modelContext.insert(hashtag)
try modelContext.save()
}
}
On top of the error discussed in the thread, using ModelActors will also trigger an old bug from over a year ago, where the UI won't refresh when an update was performed.
Has anyone found a solution yet?