I wanted to add a functionality to my App to store different Times (hour:minute) in an array of my SwiftData Model. And then to also add and remove items from this array. I ran into two problems.
The first minor problem is an error which comes from my SwiftData Model and how I initialised the Array.
import Foundation
import SwiftData
@Model
class Tapas {
var name: String
[...]
var supportTime: [Date] = []
[...]
/// Adding a relation to TapasAsana, as one Tapas has many Asanas
@Relationship(deleteRule: .cascade) var asanas = [TapasAsana]()
init(...)
}
This approach works, but I get this Error/Warning when starting the App, even though it runs perfectly fine then. I tried to search for the error and also how to better create an Array of Type Date, but I found nothing.
CoreData: Could not materialize Objective-C class named “Array” from declared attribute value type “Array” of attribute named supportTime
The other bigger problem is that my App runs fine in the Simulator, but freezes on device when I try to declare this State Var:
import SwiftUI
import SwiftData
struct EditTapasView: View {
[...]
@State private var supportTime = Date()
[...]
if showSupportTimes || !tapas.supportTime.isEmpty {
DatePicker("Supported Time:", selection: $supportTime, displayedComponents: [.hourAndMinute])
Button("Add Support Time") {
if !tapas.supportTime.contains(supportTime) {
tapas.supportTime.append(supportTime)
}
}
ForEach(0..<tapas.supportTime.count, id: .self) { supportTime in
if !tapas.supportTime.isEmpty {
Text("(tapas.supportTime[supportTime].formatted(date: .omitted, time: .complete))")
}
}
.onDelete(perform: removeSupportTime)
}
}
I had now quite some Freezes like this, always depending on declaring State vars and I don’t know how to fix this. Putting @State private var supportTime = Date(timeIntervalSince1970: 100) works, but this seems like a very hacky workaround.
For now I just bound the pickers to another Date Var from the Tapas Model, but I really would love to solve and understand this seemingly simple declaration of a Variable of type Date().
1