Core Data (CRUD) with Swift 4.2 for Beginners

Core Data is an object graph and persistence framework provided by Apple in the macOS and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows data organized by the relational entity–attribute model to be serialized into XML, binary, or SQLite stores.

Image for post
Image for post

How Does It Differ From SQLite?

Developers new to Core Data are often confused by the differences between SQLite and Core Data. If you wonder whether you need SQLite or Core Data, then you’re asking the wrong question. Remember that Core Data isn’t a database.


  • Have Data Constrains feature.
  • Operates on data, stored on disk.
  • Can Drop table and Edit data without loading them in memory.
  • Slow as compared to core data.

Core Data:

  • Don’t have Data Constraints,if required need to implement by business logic.
  • Operates on in memory.(data needs to be loaded from disk to memory)
  • Need to load entire data if we need to drop table or update.
  • Fast in terms of record creation.(saving them may be time consuming)

Additionally apart from SQLite as back-end Core data can use XML or binary format for storing data to disk.

Core Data Limitations

Even though Core Data is a fantastic framework, there are several drawbacks. These drawbacks are directly related to the nature of the framework and how it works.

Core Data can only do its magic because it keeps the object graph it manages in memory. This means that it can only operate on records once they’re in memory. This is very different from performing a SQL query on a database. If you want to delete thousands of records, Core Data first needs to load each record into memory. It goes without saying that this results in memory and performance issues if done incorrectly.

Another important limitation is the threading model of Core Data. The framework expects to be run on a single thread. Fortunately, Core Data has evolved dramatically over the years and the framework has put various solutions in place to make working with Core Data in a multithreaded environment safer and easier.

For applications that need to manage a complex object graph, Core Data is a great fit. If you only need to store a handful of unrelated objects, then you may be better off with a lightweight solution or the user defaults system.

Core Data Demo (Create, Retrieve, Update and Delete)

In order to demonstrate basics of the Core Data, let’s create single view iOS app with Core Data module selected.

Image for post
Image for post
Create project with Use Core Data

First, let’s create a new project and let’s select “Use Core Data”. Although you can add that framework for your existing project, it’s easier to add it from that place as everything will be wired up already for you.Once the project is created, you will see a file like CoreDataTest.xcdatamodeld added.

When you click it, you will see a tool that allows you to configure entities which represents data models. You can define few things for each entity there but for us Attributes and Relationships will be most important.

Image for post
Image for post
Add Entity
Image for post
Image for post
Configure Entity Name and Attributes
Image for post
Image for post

Now that, we have created a demo project with Core Data support. There are two notable changes in this Xcode template we can easily observe which are

  • The new file CoreDataCRUD.xcdatamodeld
  • The AppDelegate.swift file with Core Data Stack code

Core Data Stack

The Core Data Stack code inside the AppDelegate.swift has clear documentation in form of comments but in short, it set up the persistentContainer and save the data if there are any changes. As AppDelegate is the first file that executes as soon as app launched, we can save and fetch the context the from the Core Data Stack.
Now that, we have modelled our data in the User entity. It’s time to add some records and save it into the CoreData

Start with import CoreData to our viewcontroller.swift

Create Records to Core Data

The process of adding the records to Core Data has following tasks

  • Refer to persistentContainer from appdelegate
  • Create the context from persistentContainer
  • Create an entity with User
  • Create new record with this User Entity
  • Set values for the records for each key
Image for post
Image for post
create records through for loop to create multiple test records

Retrieve Data

The process of fetching the saved data is very easy as well. It has the following task

  • Prepare the request of type NSFetchRequest for the entity (User in our example)
  • if required use predicate for filter data
  • Fetch the result from context in the form of array of [NSManagedObject]
  • Iterate through an array to get value for the specific key

We can fetch the data from our Users entity using following code.

Image for post
Image for post

Update Data

For update record first we have to fetch/Retrieve data with predicate as same as above Retrieve data process. Then below few steps to follow

  • Prepare the request with predicate for the entity (User in our example)
  • Fetch record and Set New value with key
  • And Last Save context same as create data.
Image for post
Image for post
here in above example replace “Ankur1” with “newName”

Delete Data

For delete record first we have to find object which we want to delete by fetchRequest. then follow below few steps for delete record

  • Prepare the request with predicate for the entity (User in our example)
  • Fetch record and which we want to delete
  • And make context.delete(object) call (ref image attached below)
Image for post
Image for post
in this method we fetch record with username is ”Ankur3” and delete that record and save it.

Well, this isn’t enough to core data, there are many complex things we can do with core data tracking data changes, adding Predicates and complex relationships of databases. As you use more Core Data things get more complex.

download full source code from here

Written by

iOS Engineer

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store