Your book work app file with @main method must be like below i assume
@main
struct BookwormApp: App {
@StateObject private var dataController = DataController()
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, dataController.container.viewContext)
}
}
}
The AddView
struct AddBookView: View {
@Environment(\.managedObjectContext) var moc
@Environment(\.dismiss) var dismiss
@State private var title = ""
@State private var author = ""
@State private var rating = 3
@State private var genre = ""
@State private var review = ""
let genres = ["Fantasy", "Horror", "Kids", "Mystery", "Poetry", "Romance", "Thriller"]
var body: some View {
NavigationView {
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 {
TextEditor(text: $review)
RatingView(rating: $rating)
} header: {
Text("Write a review")
}
Section {
Button("Save") {
let newBook = Book(context: moc)
newBook.id = UUID()
newBook.title = title
newBook.author = author
newBook.rating = Int16(rating)
newBook.review = review
newBook.genre = genre
newBook.date = Date.now
try? moc.save()
dismiss()
}
}
.disabled(title.isEmpty || author.isEmpty || genre.isEmpty)
}
.navigationTitle("Add Book")
}
}
}
the datacontroller
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "Bookworm")
init() {
container.loadPersistentStores { description, error in
if let error = error {
print("Core Data failed to load: \(error.localizedDescription)")
}
}
}
}
make sure date is of type date in coredata