ios – Creating temporary SwiftData object


I have a Workout SwiftData model and a list view of workouts. The user can create a new workout by clicking on a plus button in the toolbar of the list view, which is inside a NavigationStack. The WorkoutsListView uses the model context as such:
@Environment(\.modelContext) var modelContext.

When I open the NewWorkoutView as a sheet, I want the user to be able to create a new workout and click ‘Done’ to save it (which will be reflected in the list view) or simply click the close button and discard everything. My question is, how can I do this with the SwiftData context? I have tried accessing the context in the same way as above in the sheet view, but the changes do not get reflected (even when I manually save using modelContext.save(). I have also tried passing in the container in the initialiser of the new view to create a context with this container and add the object to it; this also does not work. I would like to add that I have abstracted the context logic to the view models, i.e. I have a variable like this in my view models: var modelContext: ModelContext? = nil and I set it to the environment model context on view appear as follows: viewModel.modelContext = modelContext.

I have seen some approaches where the new object is created in the parent view and passed to the child view, but I would like to create the object ONlY if the user presses the ‘Done’ button in the child view, not beforehand. I have also tried to just create a variable in the view model of the child view and simply pass it back to the parent view using a call back method. However, this does not work as I am using the new @Bindable keyword in many of my custom subviews to bind to properties of the models. So when I use the approach I just mentioned, I get errors stating that the schema could not be found, which I assume is to do with the fact that the variable in this case is not a Model object that can be made @Bindable.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img