WWDC23 SALE: Save 50% on all my Swift books and bundles! >>

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:


Then everywhere the vm is needed i used:

@EnvironmentObject var vm: CoreDataViewModel


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



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) {
  • 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,



Save 50% in my WWDC23 sale.

SAVE 50% To celebrate WWDC23, all our books and bundles are half price, so you can take your Swift knowledge further without spending big! Get the Swift Power Pack to build your iOS career faster, get the Swift Platform Pack to builds apps for macOS, watchOS, and beyond, or get the Swift Plus Pack to learn advanced design patterns, testing skills, and more.

Save 50% on all our books and bundles!

Reply to this topic…

You need to create an account or log in to reply.

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.