Hi guys,
can anyone help me with the following.
I have declared an optional Allocation.
When I tap on the plus button the function generateNewAllocation create a new one from the default and then assign it to the optional allocation.
The problem is that the first time I tap on the + button it would assign nil as it presents a blank sheet, but if I dismiss it and tap again the value is correctly assigned.
I have checked the function which correctly returns the expected allocation, but can't figure out what is going wrong.
Thanks.
import SwiftUI
import SwiftData
struct AllocationsView2: View {
@Environment(\.modelContext) var modelContext
@Environment(\.dismiss) var dismiss
@State private var showEmployees = false
@State private var allocation: Allocation?
@State private var isSaved = false
@Query(filter: #Predicate<Allocation> {allocation in
allocation.isSetup == false
}) var allocations: [Allocation]
var body: some View {
NavigationStack {
List {
/*if let unwrappedAllocation = allocation {
Text(unwrappedAllocation.shift)
ForEach(unwrappedAllocation.areas) {area in
Text(area.name)
}
}*/
}
.navigationTitle("Allocations List")
.toolbar{
Button(action: {
modelContext.autosaveEnabled = false
let newAllocation = generateNewAllocation()
allocation = newAllocation
showEmployees = true
}) {
Image(systemName: "plus")
}
.sheet(isPresented: $showEmployees) {
if let currentAllocation = allocation {
Employees(allocation: currentAllocation, dismissView: $showEmployees, isSaved: $isSaved)
}
}
}
}
}
func generateNewAllocation() -> Allocation? {
var fetchDescriptor = FetchDescriptor<Allocation>(predicate: #Predicate { allocation in
allocation.isSetup == true
})
fetchDescriptor.fetchLimit = 1
do {
let result = try modelContext.fetch(fetchDescriptor)
let allocationFirst = result.first
let newAllocation = Allocation(id: UUID(), date: .now, shift: "Short Day", isSetup: false)
modelContext.insert(newAllocation)
if let areas = allocationFirst?.areas {
for area in areas {
let newArea = Area(id: UUID(), name: area.name, order: area.order, priority: area.priority, isActive: area.isActive)
modelContext.insert(newArea)
newAllocation.areas.append(newArea)
// print(area.name)
}
}
for area in newAllocation.areas {
print(area.name)
}
return newAllocation
} catch {
print("failed to load Default Allocation")
return nil
}
}
}