Core Data Basics in Swift

Yianni Yiannakidis
6 min readSep 14, 2022

--

What is Core Data?

A very interesting feature that gives us the ability to store and retrieve data in an app no matter if is in MacOS or in IOS is Core Data. Ιn other words to be more specific and as Apple refers to it, Use Core Data to save your application’s permanent data for offline use, to cache temporary data, and to add undo functionality to your app on a single device. Some people might be confused and think that Core Data is like a typical SQL database. That is far from true since it can only store data once entered. Meaning that Core Data keeps an object graph in the memory hence it can only work with records in the memory. You can understand this like, suppose you want to delete or update 100 records, so first you need to load all the records in the memory.

Core Data Stack

Let’s analyse now the theory behind the Core Data framework. What is the ingredients of it and what it needs to operate smoothly. The key elements and most basic contents of a Core Data Framework that work together and are :

  • the managed object model (NSManagedObjectModel)
  • the managed object context (NSManagedObjectContext)
  • and the store coordinator ( NsPersistentStoreCoordinator)

all this linked to the Persistent Container(NSPersistentContainer)

as represented in the Documentation of developer.apple.com

The Persistent Container(NSPersistantContainer)

The Persistent Container is a class that is responsible for the setup of the Core Data Stack. As show in the diagram above the Persistent Container provides access to the Managed Object Model, Managed Object Context, and Store Coordinator.

The Managed Object Model (NSManagedObjectModel)

The most basic part of the Core Data Stack is the managed Object Model. We can think Managed Object Model as the way for the entities including their attributes and relationships as the way to be connected with or to be represented with the code inside the app.

The managed Object Context (NSManagedObjectContext)

A managed object context represents a single object space, or scratch pad, in a Core Data application. A managed object context is an instance of NSManagedObjectContext . It’s the object you use to create and fetch managed objects, and to manage undo and redo operations.

The Persistent Store Coordinator(NSPersistentStoreCoordinator)

The persistent store coordinator’s role is to manage these stores and present to its managed object contexts the facade of a single unified store. When you fetch records, Core Data retrieves results from all of them, unless you specify which store you’re interested in. It has a reference to a managed object model that describes the entities in the store or stores it manages. The coordinator is the central object in a Core Data stack.

Structure of Core Data

let’s analyse the structure of Core Data in an actual demo project and we can understand how it works:

Core Data framework is one of the first choices we meet when start a new project in Xcode.

As mentioned before we have the ability to start a project with Core Data, but this is not the only option. That is why when we discover on an ongoing project we want to use the Core Data we can do that by some other steps.

Back in our example project we can see that the backbone of the Core Data in every app that we want to use is the declaration of the persistentContainer. As we told before the initiation and declaration of of the persistentContainer always happens in the AppDelegate.swift file when we choose to start a project with Core Data but when we decide that we want to use on an existing project usually we create a separate file where we instantiate a class that will be responsible for the Core Data Stack as we call it.

sample image of the Core Data Stack when the project from the beginning has Core Data enabled

Core Data Model and Core Data Model Editor

In order for the Core Data framework to integrate with an app it needs a Data model Editor. Thru this Core Data Model Editor we can create data types, relationships and develop respective class definitions Τhe main console for creating objects types, properties and relationships in the project is the Core Data Model editor

In our example project we can see that the Core Data Data Model exists in the left side of the example screenshot where of the file of the project exists and in the right side is the Core Data Model Editor where you can create the entities.

Entities and Attributes

Always when new Data Model is initiated the is no entities in the Data Model Editor created. In our sample project we have create the Customer Entity

But what is an entity? The official documentation of the developer.apple.com explains that an entity describes an object, including its name, attributes, and relationships. In our sample project the entity describes a project that is called Customer. As we saw in the screenshot above, attributes of the entity . We can think of attributes as the columns of a table in a database. Attributes store the values of a Core Data record. There are several types of attributes, such as String, Date, Integer, Float, and Boolean etc.

Relationships

Relationships are properties like attributes but instead of storing values, they store a reference to another (or the Core Data record). Before we can add a relationship, we need to add another entity. The total meaning of Relationships depends on the ability to connect to another entity and how the relationship of the two entities will work.There are one - to - one relationship between the two entities, one - to many relationship, and in more complicated apps many to many relationship. In our example project we can see the one - to - many relationship between the two entities.

the same city name for many customer

As we can see in the screenshot above from the example project the relationship one - to - many works in the logic that we can have the same city name from the entity “City” for one customer from the entity “Customer” uniquely.

every customer can have one city of living.
The relationships between the two entities can be seen from another perspective in a graphical representation.

User Defaults and when not to use CoreData

Both Core Data and User Defaults are used for storing data in an app, but there are some very big differences on when to use them. The system of User defaults is ideal for storing small pieces of data such as settings for the app or user preferences. It is nothing more than a key-value store. This facts concludes that Core Data is ideal for storing is designed and based for managing large relational data set and not for small random pieces of unrelated data.

Other Persistence Solutions

Fortunately beyond Core Data and User Defaults there are more storing data options we can use in our code. We can use SQLite or Realm. Especially Realm which is a third party framework sometimes can used more efficiently that the default Core Data regarding the store of dig and complicated datasets.

--

--