I Keep getting this error in my swift project.

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

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://D0F0E233-8D1D-4020-924B-BA56959140FD/ListModel/p10), 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. This is my actor

@ModelActor
actor ListCrudOperations:ObservableObject{
    func add(list:ListModel){
        modelContext.insert(list)
        
        try? modelContext.save()
    }
    
    func delete(identifier:PersistentIdentifier){
        guard let list = self[identifier, as: ListModel.self] else {
            print("error")
            return
        }
        if list.listType == .task{
            list.reminders!.forEach { reminder in
                TaskModel.delete(modelContext: modelContext, reminder: reminder)
                NotificationService.deleteReminders(name: reminder.title!, Id: reminder.id)
            }
        }
        else if list.listType == .subscription {
            list.subscription!.forEach({ sub in
                Subscription.delete(modelContext: modelContext, subscription: sub)
                NotificationService.deleteReminders(name: sub.ServiceName, Id: sub.id)
            })
        }
        
        else if list.listType == .link {
            list.links!.forEach ({link in
                Links.delete(modelContext: modelContext, link: link)
                NotificationService.deleteNotificationForLink(title: link.name, linkID: link.id)
            }
            )
        }
        
        modelContext.delete(list)
        try? modelContext.save()
    }
    
    
    func addReminder(reminder:TaskModel, identifier:PersistentIdentifier){
        guard let list = self[identifier, as: ListModel.self] else {
            print("error")
            return
        }
        list.reminders!.append(reminder)
        reminder.list = list
        
        try? modelContext.save()
    }
    
    func addSubscription(subscription:Subscription, identifier:PersistentIdentifier){
        guard let list = self[identifier, as: ListModel.self] else {
            print("error")
            return
        }
        list.subscription!.append(subscription)
        subscription.list = list
        try? modelContext.save()
    }
    
    func addLink(link:Links, identifier: PersistentIdentifier) {
        guard let list = self[identifier, as: ListModel.self] else {
            print("error")
            return
        }
        list.links?.append(link)
        link.list = list
        try? modelContext.save()
    }
    
    func fetchListByType(type:ListType) -> [ListModel] {
        let type = SwiftTaskSchemaV8.ListModel.ListType(rawValue: type.rawValue)!
        let fetchDescriptor = FetchDescriptor<ListModel>()
        
        do {
            let list = try modelContext.fetch(fetchDescriptor)
            let list2 = try list.filter(#Predicate { $0.listType == type })
            return list2
        }catch{
            return []
        }
    }
    
    func fetchListsForMultipleTypes(_ types: [ListType]) -> [ListModel] {
        return types.flatMap { type in fetchListByType(type: type) }
    }
    
    func fetchAllList() -> [ListModel] {
            let fetchDescriptor = FetchDescriptor<ListModel>(sortBy: [.init(\.createdDate)])
            do {
                let list = try modelContext.fetch(fetchDescriptor)
                return list
            }catch{
                return []
            }
    }
}```
and this is how i am calling it

@Environment(.modelContext) private var context

let listOperation =  ListCrudOperations(modelContainer: context.container)
            let list = ListModel(name: name, color: self.color, icon: self.icon, listType: ListModel.ListType(rawValue: picked.rawValue)!)
            Task {
                await listOperation.add(list: list)
                await MainActor.run{
                    withAnimation(.bouncy){
                        self.list.append(list)
                    }
                    CrashServices.shared.addLogs(message: "folder added")
                }
            }

I am wondering if you hold a SwiftData model created with your model actor (using ListCrudOperations.modelContext) and try to use it after the actor is released. I am guessing that the ModelContext.reset mentioned in the error message was triggered when your model actor was released...

Do you have a minimal project that can reproduce the issue? If yes, I may be able to take a look and comment.

Best,
——
Ziqiao Chen
 Worldwide Developer Relations.

No, i do not have a minimal project

I have the exact same problem. Sometimes when I build and run the app, it crashes and shows me the error. This happens randomly . Sometimes it builds fine and sometimes it crashes. Also, when it crashes and I relaunch the app without building again, it never crashes again and all data is still there. I need to publish iOS 18 update to my app but I am not sure if it's safe. Have you been able to find a solution? I wonder if this is a bug in Xcode or there is a problem with my code.

Same problem, I'm just follow a tutorial on youtube the error in this code let sample = try! container.mainContext.fetch(fetchDescriptor)[0]

import SwiftUI
import SwiftData

struct SampleView: View {
    let sample: SampleModel
    var body: some View {
        VStack{
            Text(sample.name)
                .font(.largeTitle)
            Image(uiImage: sample.image == nil ? Constants.placeholder : sample.image!)
                .resizable()
                .scaledToFit()
                .clipShape(RoundedRectangle(cornerRadius: 12))
            
        }
        .padding()
    }
}

#Preview {
    let container = SampleModel.preview
    let fetchDescriptor = FetchDescriptor<SampleModel>()
    let sample = try! container.mainContext.fetch(fetchDescriptor)[0]
    SampleView(sample: sample)

}
import UIKit
import SwiftData

@Model
class SampleModel {
    var name: String
    @Attribute(.externalStorage)
    var data: Data?
    var image: UIImage? {
        if let data {
            return UIImage(data: data)
        } else {
            return nil
        }
    }
    
    init(name: String, data: Data? = nil) {
        self.name = name
        self.data = data
    }
}

extension SampleModel {
    
    @MainActor
    static var preview: ModelContainer {
        let container = try! ModelContainer(
            for: SampleModel.self,
            configurations: ModelConfiguration(isStoredInMemoryOnly: true)
        )
        var samples: [SampleModel] {
            [
                .init(name: "Sample 1"),
                .init(name: "Sample 2"),
                .init(name: "Sample 3")
            ]
        }
        samples.forEach {
            container.mainContext.insert($0)
        }
        
        return container
    }
}```

```swift
import UIKit

enum Constants {
    static let placeholder = UIImage(systemName: "photo.fill")!
}
I Keep getting this error in my swift project.
 
 
Q