SwiftData and async functions

Hello,

I recently published an app that uses Swift Data as its primary data storage. The app uses concurrency, background threads, async await, and BLE communication.

Sadly, I see my app incurs many fringe crashes, involving EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, EXC_BREAKPOINT, etc.

I followed these guidelines:

  1. One ModelContainer that is stored as a global variable and used throughout.
  2. ModelContexts are created separately for each task, changes are saved manually, and models are not passed around.
  3. Threads with different ModelContexts might manipulate and/or read the same data simultaneously.

I was under the impression this meets the usage requirements.

I suspect perhaps the issue lies in my usage of contexts in a single await function, that might be paused and resumed on a different thread (although same execution path). Is that the case? If so, how should SwiftData be used in async scopes?

Is there anything else particularly wrong in my approach?

SwiftData and async functions
 
 
Q