So I'm watching Paul Hudson's videos about CoreData but it's honestly still confusing to me and even reading on Apple's documentation it's hard to understand what I'm doing here and what is 100% going on.
So the first thing that is done in this video is we make a xcdatamodel file, this makes sense it's just the definition for whatever data we want to store. Then he makes a DataController class with a container which is a NSPersistentContainer with the name argument being whatever the name of my xcdatamodel was, I don't fully understand this what exactly is the container for? Apple says it just sets everything up(An instance of NSPersistentContainer sets up the model, context, and store coordinator all at once.) So I guess that's that?
Then an init() is made and container.loadPersistentStores is called, what exactly is this and what are the persistent stores? I guess this is just loading the data but not sure.
Then in the Scene we call .environment(\.managedObjectContext, dataController.container.viewContext)
what exactly is this doing? Apparently we're just injecting the viewContext into the managedObjectContext or something honestly not sure what is the managedObjectContext what is the viewContext?
Then finally in some files
CodePudding user response:
Let's see if I can hit all of these:
- The
xcdatamodel
is where you describe the type of data you want to use with Core Data. When you compile your project, it gets compiled too, and the compiled version is included with your app. Core Data calls this the data model. It's similar to the schema in relational databases. Unlike relational databases, the schema and the data are stored separately. - The
NSPersistentContainer
is your starting point for working with Core Data in your app. It finds the data model, and it's how you make use of the model. You can think of it as containing both the data model and the data, so it's your starting point in code. - The
loadPersistentStores
method is how you start using Core Data in your app. This is where the container finds the data model and where it either loads the data that's already there or creates a new file to hold data. Before you do this, there might be a data model, and there might be some data in a file, but you don't have any way to use them in code yet. - The "persistent store" is Core Data's term for the file that actually holds your data. Like I mentioned earlier, the data model (roughly, the schema) and the actual data are stored separately. Persistent stores are where the data goes.
- The
viewContext
is a managed object context provided by the container. It's the one that's intended for use in your UI. ThemanagedObjectContext
variable in that line is a local variable that uses the same context.
Apple provides some really good documentation on Core Data that explains all of this and a lot more, and it sounds like it would be helpful for you to check it out.