Post

Replies

Boosts

Views

Activity

Reply to Preview crashing in custom view using SwiftData model
I actually managed to get it to work in a different way. Before, I was trying to access the static Item variables itself, but what I should have done is fetch from the model context after I inserted the static Item objects into my model. #Preview { let preview = Preview(Item.self, Category.self) preview.addExamples(Category.sampleCategories) preview.addExamples(Item.sampleItems) // SOLUTION let samples = preview.getSamples(Item.self) return NavigationStack { ItemDetailsView(item: samples[0]) .modelContainer(preview.container) } where getSamples() is a generic function defined in the Preview class as @MainActor func getSamples<T: PersistentModel>(_ model: T.Type) -> [T] { let context = container.mainContext let request = FetchDescriptor<T>() do { let samples = try context.fetch(request) return samples } catch { print("Failed to fetch model: \(error)") return [] } } Not sure if this is the "proper" way of doing it, but it worked.
Aug ’24