Non-sendable type ModelContext on MainActor

Hi, just trying to learn how to work with mainActor. I am in a need of analyzing users data with API service one a background. Whenever user saves a post into SwiftData, I need to analyze that posts asynchronously. Here is my current code, which by the way works, but I am getting warning here;

actor DatabaseInteractor {
    let networkInteractor: any NetworkInteractor = NetworkInteractorImpl()
        
    func loadUserProfile() async -> String {
        do {
            let objects = try await modelContainer.mainContext.fetch(FetchDescriptor<ProfileSwiftData>())
            
            if let profileTest = objects.first?.profile {
                return profileTest
            }
        } catch {
            
        }
        
        return ""
    }

I get a warning on let objects line.

Warning: Non-sendable type 'ModelContext' in implicitly asynchronous access to main actor-isolated property 'mainContext' cannot cross actor boundary

I’m not really a SwiftData expert, but this seems like a reasonable error to me:

  • ModelContainer is sendable.

  • ModelContext is not.

  • The container’s mainContext property is isolated to the main actor.

Your actor is… well… an actor, so it can’t access main-actor-isolated properties directly. And when it tries to access mainContext asynchronous using await, that fails because the context is not sendable.

The standard practice for doing work off the main actor is to pass around the container (which is sendable) and then create your own context on that container for the work you need to do. Well, at least that was the standard practice for Core Data, and I’m presuming that SwiftData is the same (-:

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Non-sendable type ModelContext on MainActor
 
 
Q