iOS Development

ios – Creating non permanent SwiftData object

Spread the love


I’ve a Exercise SwiftData mannequin and an inventory view of exercises. The consumer can create a brand new exercise by clicking on a plus button within the toolbar of the checklist view, which is inside a NavigationStack. The WorkoutsListView makes use of the mannequin context as such:
@Surroundings(.modelContext) var modelContext.

After I open the NewWorkoutView as a sheet, I need the consumer to have the ability to create a brand new exercise and click on ‘Carried out’ to put it aside (which will likely be mirrored within the checklist view) or just click on the shut button and discard every little thing. My query is, how can I do that with the SwiftData context? I’ve tried accessing the context in the identical approach as above within the sheet view, however the modifications don’t get mirrored (even after I manually save utilizing modelContext.save(). I’ve additionally tried passing within the container within the initialiser of the brand new view to create a context with this container and add the item to it; this additionally doesn’t work. I wish to add that I’ve abstracted the context logic to the view fashions, i.e. I’ve a variable like this in my opinion fashions: var modelContext: ModelContext? = nil and I set it to the atmosphere mannequin context on view seem as follows: viewModel.modelContext = modelContext.

I’ve seen some approaches the place the brand new object is created within the dad or mum view and handed to the kid view, however I wish to create the item ONlY if the consumer presses the ‘Carried out’ button within the youngster view, not beforehand. I’ve additionally tried to only create a variable within the view mannequin of the kid view and easily go it again to the dad or mum view utilizing a name again technique. Nonetheless, this doesn’t work as I’m utilizing the brand new @Bindable key phrase in a lot of my customized subviews to bind to properties of the fashions. So after I use the strategy I simply talked about, I get errors stating that the schema couldn’t be discovered, which I assume is to do with the truth that the variable on this case will not be a Mannequin object that may be made @Bindable.

Leave a Reply

Your email address will not be published. Required fields are marked *