I'm getting a crash in the preview canvas only - runs fine in the simulator. Pretty sure I've copied Paul's code exactly, but cannot get past this error:
Fatal error in ModelContainer.swift - failed to find a currently active container for Book.
My Code
Main App Bundle:
import SwiftUI
import SwiftData
@main
struct SwiftDataSandboxApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
.modelContainer(for: Book.self, inMemory: true)
}
}
ContentView
import SwiftData
import SwiftUI
struct ContentView: View {
@Environment(\.modelContext) var modelContext
@Query var books: [Book]
@State private var showingAddScreen = false
var body: some View {
NavigationStack {
Text("Count: \(books.count)")
.navigationTitle("Bookworm")
.toolbar {
ToolbarItem(placement: .topBarTrailing) {
Button("Add Book", systemImage: "plus") {
showingAddScreen.toggle()
}
}
}
.sheet(isPresented: $showingAddScreen) {
AddBookView()
}
}
}
}
#Preview {
ContentView()
}
AddBookView
import SwiftUI
struct AddBookView: View {
@Environment(\.modelContext) var modelContext
@Environment(\.dismiss) var dismiss
@State private var title = ""
@State private var author = ""
@State private var rating = 3
@State private var genre = "Fantasy"
@State private var review = ""
let genres = ["Fantasy", "Horror", "Kids", "Mystery", "Poetry", "Romance", "Thriller"]
var body: some View {
NavigationStack {
Form {
Section {
TextField("Name of book", text: $title)
TextField("Author's name", text: $author)
Picker("Genre", selection: $genre) {
ForEach(genres, id: \.self) {
Text($0)
}
}
}
Section("Write a review") {
TextEditor(text: $review)
Picker("Rating", selection: $rating) {
ForEach(0..<6) {
Text(String($0))
}
}
}
Section {
Button("Save") {
let newBook = Book(title: title, author: author, genre: genre, review: review, rating: rating)
modelContext.insert(newBook)
dismiss()
}
}
}
.navigationTitle("Add Book")
}
}
}
#Preview {
AddBookView()
}
Book
import Foundation
import SwiftData
@Model
class Book {
var title: String
var author: String
var genre: String
var review: String
var rating: Int
init(title: String, author: String, genre: String, review: String, rating: Int) {
self.title = title
self.author = author
self.genre = genre
self.review = review
self.rating = rating
}
}
I've also tried initiating the modelContainer differenly in the main app file as I found in other suggestions online. This did not change the crash.
@main
struct SwiftDataSandboxApp: App {
let modelContainer: ModelContainer
init() {
do {
modelContainer = try ModelContainer(for: Book.self)
} catch {
fatalError("Could not initialize ModelContainer")
}
}
var body: some Scene {
WindowGroup {
VStack {
ContentView()
}
}
.modelContainer(modelContainer)
}
}
Any help is apprectiated!!