I have a list of swiftdata objects I want to fetch and show in a swift UI list. My problem is the swiftdata object in my DB is not the object I directly want to use in my view. I want to map it to a different viewModel and use that which makes my life wayyy easier.
problem is every single example I see online of swift data, just uses the magic @Query operator to get their data, and then directly show it on the UI.
What's the best way for me to load the data on initialization but map it to a different type? I've tried this, but it just crashes.
init() {
do {
modelContainer = try ModelContainer(for: MY_DATA_CLASS.self)
} catch {
fatalError("Could not initialize ModelContainer")
}
let serverList = FetchDescriptor<MY_DATA_CLASS>(
sortBy: [SortDescriptor(\.displayOrder)]
)
do {
viewModels = try modelContext.fetch(serverList).map {
ViewModel(server: $0)
}
} catch {
print(" WHAT THE HECKKK: " + error.localizedDescription)
}
}
NSFetchRequest could not locate an NSEntityDescription for entity name ....
any suggestions greatly appreciated. Using @query works fine so I know the rest of the DB is setup correctly.