it will crash, when i Use SwiftData in Preview

this is my code

import SwiftUI
import SwiftData

@Model
class TestItemTotal {
    var name: String
    init(_ name: String) {
        self.name = name
    }
}

struct TestItemTotalDetail: View {
    var currentItem: TestItemTotal
    
    var body: some View {
        VStack {
            Text(currentItem.name)
        }
    }
    
    init(currentItem: TestItemTotal) {
        self.currentItem = currentItem
    }
}

#Preview {
    var item = TestItemTotal("james qq")
    return TestItemTotalDetail(currentItem: item)
}

Crash

it will crash ,when #preview use Xcode

fix Crash

Remove @Model string , it will not crash , when #preview use Xcode ,

but i can't remove @Model String , because i will to processing data by SwiftData

the crash info

I don't know how to fix this crash .

Creating an instance of the model class TestItemTotal without a model context (from a container) present will crash the preview. To fix this you can change your preview code to:

#Preview {
    do {
        let config = ModelConfiguration(isStoredInMemoryOnly: true) // Store the container in memory since we don't actually want to save the preview data
        let container = try ModelContainer(for: TestItemTotal.self, configurations: config)
        var item = TestItemTotal("james qq")
        
        return TestItemTotalDetail(currentItem: item) 
            .modelContainer(container)
    } catch {
        return Text("Failed to create preview: \(error.localizedDescription)")
    }
}
it will crash, when i Use SwiftData in Preview
 
 
Q