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      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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.