SwiftUI and Core Data - Pass Data between views the correct way

Hello everyone,

I am new to Core Data and I am trying to implement it on my app. I am concerned with memory leaking and I want to make sure that I am doing things the proper and safer way

At the moment I have two views. Putting it simply, I have one where I create the object and the other where I just display the attributes.

I have a var - that is the type of my Entity in Core Data and I declare it like this:

Code Block
@State var observation: Observation?


Then inside my view when I press the button I have:

Code Block
let newObservation = Observation(entity: Observation.entity(), insertInto: managedObjectContext)
newObservation.id = UUID()
newObservation.speciesName = finalLabel
...
do {
try managedObjectContext.save()
observation = newObservation
} catch {
activeAlert = .canNotSaveCoreData
showAlert.toggle()
}


I then send the observation object to my other view like this:

Code Block
Details(sheetIsOpen: $sheetIsPresented, observation: observation!)


What intrigue me is the way I am sending the observation object. Is this correct / the standard way?

What should I be doing differently?

Thank you for your help!




Did you consider using @EnvironmentObject ?
I did, but how would I get persistence with environment object?

The way I am doing it, is it correct?

Thank you!

The way I am doing it, is it correct?

Nothing wrong can be found in your currently shown code. (Except the forced unwrapping, which may be another topic.)
There may be something wrong about how you are using it, but the code is not shown.
SwiftUI and Core Data - Pass Data between views the correct way
 
 
Q