I am working on implementing CoreData/Cloudkit in my project. It is built in SwiftUI using the MVVM architecture. I am stuck on the part where I am saving/adding something to CoreData, in the Xcode template provided by Apple, this is done in the ContentView file, however to me this feels like something that should be done in the ViewModel. Is that correct?
For additional context, my project is a simple game and the score is calculated in the viewModel. The score is then immediately displayed to the user through the ContentView. I also want to be able to save the score to a Leaderboard CoreData object. Since most of the work done with the score is done in the viewModel, it makes most sense to me for the saving to be handled there instead of in the view.
The template does the saving through the following code
let newItem = Item(context: viewContext)
newItem.timestamp = Date()
do {
try viewContext.save()
where viewContext is @Environment(\.managedObjectContext) private var viewContext
How would I go about doing this in the ViewModel since I believe @Enviroment is for SwiftUI.
PersistanceController. Otherwise, as you end up with more view models, you are simply duplicating code.