BLACK FRIDAY SALE: Save big 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:

.environmentObject(vm) 

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?

   

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

   

Hacking with Swift is sponsored by RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn more

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

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.