iOS 18 SwiftData ModelContext reset

Since the iOS 18 and Xcode 16, I've been getting some really strange SwiftData errors when passing @Model classes around.

The error I'm seeing is the following:

SwiftData/BackingData.swift:409: Fatal error: This model instance was destroyed by calling ModelContext.reset and is no longer usable.
PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata://34EE9059-A7B5-4484-96A0-D10786AC9FB0/TestApp/p2), implementation: SwiftData.PersistentIdentifierImplementation)

The same issue also happens when I try to retrieve a model from the ModelContext using its PersistentIdentifier and try to do anything with it. I have no idea what could be causing this.

I'm guessing this is just a bug in the iOS 18 Beta, since I couldn't find a single discussion about this on Google, I figured I'd mention it.

if someone has a workaround or something, that would be much appreciated.

@SplittyDev, your update was was very helpful, thank you!

I have two model containers: One for previews with in-memory storage only, and one for development with proper on-disk storage.

For that part, here's what I'm doing:

extension ModelContainer {
static var shared: ModelContainer = {
if ProcessInfo.isPreview { return preview }
// ...
}()
static var preview: ModelContainer = {
// ...
}()
}
public extension ProcessInfo {
static var isPreview: Bool {
return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}
}

With your answer and this, I managed to get it all working how I was hoping. :D

iOS 18 SwiftData ModelContext reset
 
 
Q