UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

ViewModel doesn't reach the sheetView when using @EnvironmentObject

Forums > SwiftUI

I'm building an app and run into some problems. If I want to access data from a tabView it's no problem. Also a linked view is no problem, but I can't access the viewModel in a sheet.

I have an addView(sheet) that has a some entry fields. When the user hits the save button the data is saved to coreData with a function in the ViewModel. Also in the ViewModel is a function to connect two coreData entities to eachother (think company and employee). But this function doesn't work in the sheet by using the same save-button. It looks like the arrays aren't passed.

To make the ViewModel available in every tabView i used:

@StateObject private var vm: CoreDataViewModel = CoreDataViewModel() 

in the contentView and on every tabItem:

.environmentObject(vm) 

Then everywhere the vm is needed i used:

@EnvironmentObject var vm: CoreDataViewModel

2      

So accoording to you adding Codable conformance for @Published properties should solve the problem?

2      

hi,

unless something's changed recently ... i'm not into iOS 16 and SwiftUI 4 stuff yet ... a sheet does not inherit the environment of the view that creates it.

  • in your .sheet modifier, consider injecting the view model directly into the environment of the view that is opened.

    .sheet(isPresented: $isPresented) {
    AddView()
        .environmentObject(vm)
    }
  • alternatively, you could pass the view model directly as an argument, where the viewModel variable in the AddView is marked as an @ObservedObject.

    .sheet(isPresented: $isPresented) {
    AddView(viewModel: vm)
    }

hope that helps,

DMG

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.