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

SOLVED: Could I add .environment(\.managedObjectContext, persistenceController.container.viewContext) to a Class or a Struct?

Forums > Swift

I am learning Core Data, I feel it's really cool to use @Environment to access Core Data.

But I want to creat a Class to add some items to Core Data.

Could I add .environment(.managedObjectContext, persistenceController.container.viewContext) to a Class or a struct? Or this is some similar way to access Core Data as easy as @Environment(.managedObjectContext) var moc

2      

The majority of your Core Data work involves using the managed object context aka moc. This means the observable object (class) will have to get access to the moc in some way. You can use injection option that works by passing the moc you want to use into the observable object when it is created. Example: Managed Object Context -> ObservableObject -> SwiftUI View

let moc = MyContainer().persistentContainer.viewContext
let oo = MyObservableObject(moc: moc)
MyView(oo: oo)

3      

Hi @ygeras Thanks for your reply, please forgive my ignorance, I am learning. let me explain what I thought more detail.

use @Environment(.managedObjectContext) var moc, I feel the code looks so natrure.

In this Paul's Article "How to add Core Data objects from SwiftUI views" https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-core-data-objects-from-swiftui-views

we could get access the by one line of code let language = ProgrammingLanguage(context: managedObjectContext) which looks so cool.

Other article when add object to Core Data, it has to use forKey, like this

let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)

newUser.setValue("Abhishek", forKey: "username")
newUser.setValue("2311", forKey: "password")
newUser.setValue("21", forKey: "age")

How to make code as simple as the first one?

2      

No worries at all. So if you go through the same preparatory setup as in Paul's video. That is, create entity Users with attributes username, password, and age as well as setup moc. You will be able to do absolutely the same here.

let newUser = Users(context: managedObjectContext)
newUser.username = "Abhishek"
newUser.password = "23111"
newUser.age = 21 // or if set it up as String "21"

2      

Hi @ygeras ,

Thank you, I found it.

static func loadDataToCD(moc: NSManagedObjectContext) {
           let newUser = User(context: moc)
}

I know it will call this func somewhere else, but just tell moc you are NSManagedObjectContext, then I can get the User Class, how it happened?

is that magic?

2      

Behind the scenes CoreData creates Entity as a Class. When you create an object from that class, you need context where you will work with your data. Imagine it as space in memory. The NSManagedObjectContext is provided to you by the NSPersistentContainer. It’s giving you a space in memory (context) to work with your data objects before committing it (saving it) to persistent storage. The NSManagedObjectContext is not automatically filled up with all the data from your persistent store. Think of it as a temporary place where you can fetch, create, change, and destroy things within it. So only when requested will the persistent container load data into the managed object context. With function in your example you pass the reference to that space in memory and use it to create your object. So there is no real magic but Core Data developers' sweat, "blood" and sleepless nights to make it so easier for us to work with data :)

2      

Could I add .environment(.managedObjectContext, persistenceController.container.viewContext) to a Class or a struct?

No, the environment only exists in a View.

2      

Hi @ygeras thank you for you detail explaination, I feel I got the courage to dig deeper.

2      

Hacking with Swift is sponsored by RevenueCat.

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

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.