Core Data: Fundamentals

Jul 19 2022 · Swift 5.5, iOS 15.4, Xcode 13.3.1

Part 1: The Core Data Stack

02. The Core Data Stack

Episode complete

Play next episode

About this episode

Leave a rating/review

See forum comments
Cinema mode Mark complete Download course materials
Previous episode: 01. Introduction Next episode: 03. Managed Object Model
Transcript: 02. The Core Data Stack

Before we talk about each class and the roles they play it’s important to spend some time talking about what Core Data is and isn’t. If you’re coming from a web background there are a couple different ways that you might store user data.

You might interact with a database directly. There are different kinds of databases these days but regardless of the type it often comes with some sort of query language that you can use to interact with the database.

If this is the case when a user fetches or saves data you are executing queries directly against the database and parsing the result into models that you can then use.

Alternatively, you could use an object relational mapping framework or an ORM. With an ORM, instead of writing queries using the database’s query language, you execute queries written in your app’s programming language. The ORM framework handles the job of translating those commands into the database query that the database expects.

Core Data doesn’t follow either of these approaches, at least not entirely. Core Data is a combination of an object graph manager and a persistence framework. So what’s an object graph?

If you’ve written an app that displays data to the user, you’ve probably created a class or two to model this data. For example, let’s say you’re creating an app to keep track of the books you read. You could start simple and have a Book type.

Books have authors and since our app sorts by an author, you could have a type to represent that. A book could also have a genre.

If your model is to be accurate then you also need to reference all the books that an author has written, and the different genres they encompass. As this app grows, the different objects and their relationships to one another start to become more complex.

This is what we call an object graph - the various objects in the model layer along with their relationships to one another and the rules that govern these relationships.

This is part of what Core Data does for you - it manages the object graph.

But once you have instances of these objects in the graph, you also need to save, update and delete them based on all the user preferences and interactions. This is the second job of Core Data - to provide a persistence framework that handles that set of functionality.

That framework contains several different classes, each of which takes responsibility for a portion of the framework. When combined, these classes are commonly referred to as the Core Data Stack.

In the next video, you’ll take a look at the first part of the stack - the managed object model.