Swift 6, SwiftData modelContext.save() Crashes, Does not AutoSave

I took one of my apps and have gone through the process of making it compatible with Swift 6. I started with Swift 5 and Complete Concurrency Checking and eliminated every warning. I flipped the switch to Swift 6 and I have no compile errors and no warnings. I also created a ModelActor and created async functions to fetch, delete, get an object's persistentID and save model objects. My SwiftData model has a notes property and the user can update or add onto the notes and resave the model object. The app crashes when I save the changes using an explicit save operation. However, the next time the app is launched, the changes did propagate. If I do not use the explicit save operation, the system does not auto-save and does not crash.

When I switched back to Swift 5 and tried it out, I was able to save without a crash. I did need to use an explicit save operation though.

However, I am now getting 3 warnings like the following.

Type 'ReferenceWritableKeyPath<MyModel, Optional<String>>' does not conform to the 'Sendable' protocol; this is an error in the Swift 6 language mode

The line of code that produced that warning is `let fetchDescriptor = FetchDescriptor<MyModel>(sortBy: [SortDescriptor(\MyModel.title)])

However, when I flip the switch back to Swift 6, the three warnings go away and I have zero warnings under Swift 6.

Answered by SpaceMan in 801014022

Problem solved by insuring that the task is on the main actor. I've removed the feedback.

I now understand the the warnings go away under Swift 6 as 'InferSendableFromCaptures' has been enabled. I still have the crash. Guess I better dig in.

I've discovered where the crash is occurring. I have an @objc function called updateView() that is fired when the view controller detects NSPersistenStoreRemoteChange. As soon as I save an object in another view, the update fires and the app crashes.

NotificationCenter.default.addObserver(self, selector: #selector(updateView(_ :)), name: .NSPersistentStoreRemoteChange, object: nil)

The crash does not occur using Swift 5.

I have two screenshots of the threads, one under Swift 5 and one under Swift 6. I set a breakpoint in the updateView method. The Swift 5 run gets to the breakpoint. The Swift 6 run does not and crashes.

Swift 5

Swift 6

Any help would be most appreciated. Or maybe this is ripe for a bug report?

I filed a feedback on the crash. It's FB14766558.

Accepted Answer

Problem solved by insuring that the task is on the main actor. I've removed the feedback.

Swift 6, SwiftData modelContext.save() Crashes, Does not AutoSave
 
 
Q