The crash occurs with just #Preview { ContentView().modelContainer(for:) } when I don't use traits, but I normally use traits, here's one I use:
struct SampleData: PreviewModifier {
static func makeSharedContext() throws -> ModelContainer {
let schema = Database.schema
let configuration = ModelConfiguration(isStoredInMemoryOnly: true)
let modelContainer = try ModelContainer(for: schema, configurations: configuration)
return modelContainer
}
func body(content: Content, context: ModelContainer) -> some View {
content.modelContext(context.mainContext)
}
}
I also use this in my traits:
func body(content: Content, context: ModelContainer) -> some View {
content.modelContainer(context)
}
When I removed predicates that accesses a struct's sub property or fetching model in a generic function that lets me access id, then it stops crashing any of my previews with/without traits, I can use SwiftData without issues.
I decided to create a separate project and ran this code below, which was enough to crash previews for my Mac Studio (black screen and a red x mark).
I'm noticing now that it doesn't crash if I remove .modelContainer(_:), but I won't be able to use SwiftData.
import SwiftData
import SwiftUI
#Preview { ContentView().modelContainer(for: Media.self) }
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query(filter: Media.predicate) private var models: [Media]
var body: some View {
VStack {
Button("Models: \(models.count)") {
let media = Media(type: .init(value: .random(in: 0..<3)))
modelContext.insert(media)
try? modelContext.save()
}
ForEach(models) { Text($0.id.uuidString) }
}
}
}
@Model class Media: Identifiable {
@Attribute(.unique) var id: UUID = UUID()
@Attribute var type: MediaType
init(type: MediaType) {
self.type = type
}
static var predicate: (Predicate<Media>) {
let image = MediaType.image.value
let predicate = #Predicate<Media> { media in
media.type.value == image
}
return predicate
}
}
struct MediaType: Codable, Equatable, Hashable {
static let image: MediaType = .init(value: 0)
static let video: MediaType = .init(value: 1)
static let audio: MediaType = .init(value: 2)
var value: Int
}
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
I'm gonna see if my iPad does the same...
Also, I mentioned this in my updated bug report, but it turns out I always had this issue since Xcode 16, my preview constantly crashed and using legacy mode fix it. I was able to pin point the cause with Xcode 16.3 (it mentions Fatal Error in Schema.swift in 16.3, instead of Fatal Error in DataUtilities.swift before).