SwiftData data created for previewing crashes the app sometimes

I am creating an app for organising books using SwiftUI and SwiftData. Adapting the code from Building a document-based app using SwiftData, I created the following model container for use in SwiftUI views (or the simulator).


@MainActor
let previewData: ModelContainer = {
    do {
        let bookSchema = Schema([Book.self])
        let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
        let container = try ModelContainer(
            for: bookSchema,
            configurations: configuration)
        let modelContext = container.mainContext
        if try modelContext.fetch(FetchDescriptor<Book>()).isEmpty {
        var books = [
            Book(name: "A book", year: 2024),
            Book(name: "On Film Making", author: "Alexandar Mackendrick", year: 2005, isbn: try! validateISBN(isbn: "9780571211258"))
        ]
            for book in books {
                modelContext.insert(book)
                print("Inserted book")
            }
        }
        return container
    } catch {
        fatalError("Failed to create container")
    }
}()

This builds fine, however, when I run it in previews, it crashes about 50% of the time with the following error:

CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLSaveChangesRequestContext: 0x60000370ca80> , -[__NSDictionaryM UTF8String]: unrecognized selector sent to instance 0x60000024c760 with userInfo of (null)
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSDictionaryM UTF8String]: unrecognized selector sent to instance 0x60000024c760'

When researching the problem, I only found this GitHub issue from 2018, which was never resolved (it was closed due to inactivity). The issue comments suggest that it is a Core Data issue caused by a "dangling pointer" and "memory and race conditions".

This is the definition of the Book model. Most of the values are optional because the data will be entered automatically from sources that may have incomplete data.

@Model
final class Book {
    var name: String?
    var author: String?
    var year: Int?
    var isbn: ISBN?
    var shelf: Shelf?
    var collections: [Collection]
    var marcXML: Data?
    let dateCaptured: Date()
    init(name: String? = nil, author: String? = nil, year: Int? = nil, isbn: ISBN? = nil, shelf: Shelf? = nil, marcXML: Data? = nil, collections: [Collection]? = nil) {
        self.name = name
        self.author = author
        self.year = year
        self.isbn = isbn
        self.shelf = shelf
        self.dateCaptured = Date()
        self.marcXML = marcXML
        self.collections = collections ?? []
    }
    
}
SwiftData data created for previewing crashes the app sometimes
 
 
Q