I've implemented CoreData in production identically to the suggestion by HackingWithSwift: https://www.hackingwithswift.com/quick-start/swiftui/how-to-configure-core-data-to-work-with-swiftui
This is by far the most common crash reason affecting almost 1% of all users. I was reviewing the organizer crash log in a TechTalk without any results. Therefore, respect if any of you knows the cause:
Here is the specific code used, but as I said, it's as described in the HackingWithSwift article:

I appreciate any help, I've been fighting with this for a while, and I assume others must have the same issue since HackingWithSwift is a popular site. Thank you so much!
class GroupedPersistentContainer: NSPersistentContainer {
enum URLStrings: String {
case group = "group.app"
}
override class func defaultDirectoryURL() -> URL {
let url = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: URLStrings.group.rawValue)
if !FileManager.default.fileExists(atPath: url!.path) {
try? FileManager.default.createDirectory(at: url!, withIntermediateDirectories: true, attributes: nil)
}
return url!
}
}
Here is an example of how I use core data in prod for background tasks. This function is only for demonstration but the coding style might be the cause of the issue:
func backgroundCoreDataExample(userinfo: UserInfoProperties) {
Task {
// some api call or something else
PersistenceController.shared.container.performBackgroundTask({ context in
guard let user = User.fetch(viewContext: context) else {
completion(false)
return
}
user.userid = Int64(userinfo.userid)
context.saveIfPossible()
DispatchQueue.main.async {
let viewContext = PersistenceController.shared.container.viewContext
if let user = User.fetch(viewContext: viewContext) {
print(user.userid)
}
}
})
}
}
Here is how I am initialising the singleton
@main
struct YourApp: App {
let persistenceController = PersistenceController.shared
// …
}

It seems to me that this is a deadlock:
As shown in your stack trace,
init(inMemory:)is executed on the main thread, but cannot continue (sqlite3LockAndPrepare), since another thread also runs theinit, and locks the database.Thus I suspect that you are using your singleton
PersistenceController.sharedalso on some background thread that runs concurrently to your main thread.Maybe you could check this.
EDIT:
It is difficult to make a suggestion without knowing the architecture of your app. Maybe you can do the following:
Initialize the singleton very early in your app, e.g.:
SwiftUI:
UIKit:
Start the background threads only after
persistenceControllerhas been initialized.