I have created this TimerListView
with (+) button on the toolbar. I'm able to create a new Timer
entity using TimerEditView.
But if in the TimerEditView
I try to delete the entity clicking on "Dismiss" button, an error will be raised.
import SwiftUI
import CoreData
struct TimerListView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(
sortDescriptors: [NSSortDescriptor(keyPath: \Timer.id, ascending: true)],
animation: .default)
private var timers: FetchedResults<Timer>
@State private var isPresentingSheet = false
@State private var showFavoritesOnly = false
@State private var sheetView: SheetView = .setting
@State var newTimerToAdd: Timer = Timer()
var body: some View {
NavigationView{
List {
ForEach(timers) { timer in
NavigationLink(destination: TimerDetailView(timer: timer)) {
TimerCardView(timer: timer)
}
}
}
.navigationTitle("Timer")
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button(action: {
newTimerToAdd = Timer(context: viewContext)
newTimerToAdd.id = UUID()
newTimerToAdd.name = "Timer name"
newTimerToAdd.secondsOn = 0
newTimerToAdd.secondsOff = 0
newTimerToAdd.rounds = 1
newTimerToAdd.cycles = 1
newTimerToAdd.secondsOffBetweenCycles = 0
newTimerToAdd.favourite = false
sheetView = .newTimer
isPresentingSheet = true
}) {
Label("New timer", systemImage: "plus")
}
}
}
.sheet(isPresented: $isPresentingSheet) {
if (sheetView == .newTimer) {
NavigationView {
TimerEditView(timer: newTimerToAdd)
.toolbar {
ToolbarItem(placement: .cancellationAction) {
Button("Dismiss") {
viewContext.delete(newTimerToAdd)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
viewContext.rollback()
//print("Failed to save context \(nsError.localizedDescription)")
let nsError = error as NSError
fatalError("CAZZO Unresolved error \(nsError), \(nsError.userInfo)")
}
isPresentingSheet = false
}
}
ToolbarItem(placement: .confirmationAction) {
Button("Add") {
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
//timers.append(newTimerToAdd)
isPresentingSheet = false
//newTimer = Timer()
}
}
} // .toolbar
} // NavigationView
} else {
NavigationView {
SettingsView()
.toolbar {
ToolbarItem(placement: .confirmationAction) {
Button("Salva") {
isPresentingSheet = false
}
}
}
}
}
} //.sheet
}
}
}