[ad_1]
I’ve a view, the place i can add a brand new entry to CoreData. The title for that entry can’t be null, which will be seen within the ViewModel. If somebody tries so as to add a brand new entry with out a title, they’re offered with an error. Now, each time the error pops up, it dismisses itself.
The View:
struct AddProductPopover: View {
@Setting(.presentationMode) var presentationMode
@StateObject var prodPopViewModel = AddProductPopoverViewModel()
var physique: some View {
NavigationView {
Checklist {
// some gadgets ...
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
prodPopViewModel.saveProduct()
// if saving fails resulting from an empty title, the dismissal remains to be referred to as earlier than the error is displayed
presentationMode.wrappedValue.dismiss()
}
.alert(isPresented: $prodPopViewModel.showAlert) {
Alert(
title: Textual content("Product Title can't be empty!"),
message: Textual content("Please specify a reputation on your new Product.")
)
}
}
}
}
}
The ViewModel:
class AddProductPopoverViewModel: ObservableObject {
var managedObjectContext = PersistenceController.shared.container.viewContext
@Revealed var newProductName: String = ""
@Revealed var newProductVendor: String = ""
@Revealed var newProductCategory: String = ""
@Revealed var newProductStoredQuantity: Int = 0
@Revealed var showAlert = false
func saveProduct() {
// if title shouldn't be nil saves the brand new product to CoreData
if !newProductName.isEmpty {
let newProduct = ProductEntity(context: managedObjectContext)
newProduct.productName = newProductName
newProduct.id = UUID()
newProduct.productVendor = newProductVendor
newProduct.productCategory = newProductCategory
newProduct.productStoredQuantity = Int32(newProductStoredQuantity)
PersistenceController.shared.save()
} else {
showAlert = true
}
}
I’ve found out, that challenge lies within the View within the Button Save motion. Each time the verify within the ViewModel fails, it units the boolean required for the alert to true. Nevertheless, after setting that boolean to true, it returns to the view first and completes the subsequent step within the Button Motion, which is dismissing the present view earlier than it then lastly triggers the Alert. This execution order ends in the Alert to be dismissed. Nevertheless, the alert shouldn’t be dismissed. Dismissing ought to solely occur if saving to CoreData has been successfull.
Button("Save") {
prodPopViewModel.saveProduct()
presentationMode.wrappedValue.dismiss()
}
What adjustments would I have to make to skip the dismissing line in case the boolean is ready to true? I considered together with the dismissal within the ViewModel. Nevertheless, that will violate the MVVM idea I am making an attempt to comply with.
[ad_2]
