Show Menu

Looking for an iOS Developer?

Submit your 30 day Job Listing for FREE

In this Swift 2 Core Data tutorial I will endeavor to teach you everything you need to know in order to Create a Core Data Application and help you get to grips with the overall architecture.

Topics in this tutorial will cover:

Swift 2 Core Data

This tutorial will cover Core Data in Swift 2. If you are looking for an Objective-C Version. There is a tutorial here: Connecting to an online service and persisting data with CoreData

What is Core Data?

Core Data is a set of Tools (referred to as a Framework) that will allow you to save (referred to as Persist) and Retrieve the data in your iOS application to the iOS Device that your application is running on.

It does this by implementing something called ORM (Object Relational Mapping). This might sound scary but do not worry, you will learn that us developers like to give weird and long names to things to confuse people. This basically just means that Core Data will interact with your Swift Objects without you having to worry about the code that is handled. Core Data will handle how the data from your Swift Objects is stored and retrieved from the persisted data stores like relational databases from SQLite or flat files.

It’s my recommendation that you invest some time in getting to understand the Core Data Architecture. Because you cannot see what Core Data is doing in the background you could easily get lost in your own application and cause unknown errors. It’s always a good idea to comment your code thoroughly (At least whilst in production).

For more information on Core Data, check out the Apple Documentation: What is Core Data?

Creating a Core Data App in Swift

The rest of this Swift 2 Core Data Tutorial assumes that you have a basic understanding of the Swift programming language and that you know how to navigate your Xcode at least to a basic level. If you need a brush up on Swift check out this tutorial:

Ok, so go ahead and open Xcode. When you see the welcome screen, click Create New Project.

core data tutorial xcode

This will then load up a new dialogue window. On the Left hand side chose Application under the iOS Heading and select the Master Detail Application. Click Next.

core data tutorial master detail

You will then be presented with a final dialogue asking you to add in options for your project like Project Name, Organisation name etc. For a test application these are not that important just remember to make sure you check Use Core Data. This is what I have:

core data tutorial options

Once you click next, you will have to chose the location that you want to save your project. Find somewhere and then click Create. Voila! you have just created a blank Master Detail Application.

If you Run your app now you will see:

core data tutorial run app

Now you might think that nothing has happened and this is just a blank app. But, what has actually happened is that without you having to type any code or drag in any elements Core Data has persisted data, saved it to the SQLite Database and created this view automatically for you. See what I mean about potentially getting lost when Core Data takes over?

Core Data: Concepts & Terminology

Just like any programming language there are terms that can get you into a little frustrated bother.

Here is a simplified version of the Core Data Architecture. Some of these terminologies might not make sense to you right now, but do not worry. My plan is to make sure you understand by the end of this Swift 2 Core Data tutorial.

core data architecture

As you can see form the above diagram, there are 5 key concepts that we should focus on and will in this tutorial:

  • Data Model
  • Persistent Store
  • Persistent Store Coordinator
  • Managed Objects Context
  • Fetch Request

Core Data Model

So, what is a Data Model? Well, A Data Model organizes data elements and standardizes how the data elements relate to one another. Since data elements document real life people, places and things and the events between them, the Data Model represents reality. For Core Data, the Data model helps to define the structure of objects, how those objects are organised, how the objects are related and how they behave with each-other.

Remember when you first created your application and you checked the box that said Use Core Data? Well What Xcode did with that was create your a Core Data File. In your Project Navigation Pane you should be able to see: CoreDataApp.xcdatamodel.

If you select this file you will then be able to see the Core Data Model Editor. You will also notice that a new pane has opened up along the left side. This is referred to as the Top-Level Components pane. This new pane outlines the entities, fetch requests and the configurations that are defined in the Data Model. This brings us to Core Data Entities…

Core Data Entities

What are Entities? Well.. an entity is rather like a table in a database. When you select the entity, you will see that an entity can have attributes, relationships, and fetched properties.

Now we need to create an entity to work with. At the bottom of the data model editor, click the Add Entity button. This will add an entity with name Entity. It will show up in the Entities section on the left of the data model editor. Change the entity’s name to Event by double-clicking it in the Entities section.

Note: there is a rule about naming when you want to create entities and that is that the entity name must begin with a capital letter.

If you select this entity in the Top-Level Components pane that we discussed earlier you will now be able to see three tables: Attributes,Relationships,Fetched Properties. You will also see options on how to add each of these.

Core Data Properties

Properties belong to an entity and an entity can consist of many properties. You can use the Inspector pane to “inspect” and change these. There are three different types of properties: Attributes,Relationships,Fetched Properties. When you select the entity in the Model Editor – The details of that property will appear in the Inspector Pane.

Core Data Attributes

Attributes serve the same purpose in Core Data as instance variables do in a Swift Class. That is they both hold data. When creating entities, the property that you will use the most will be Attributes. You will notice that the Event entity that we created earlier has an attribute named timeStamp (Which conforms to NSDate), which if you haven’t guessed holds the date and time of the Event instance.

Every Attribute has a type which can be set in one of two ways. The first is to change it when you are in the Model Editor using the table style you can change the type in the attributes table in the Detail Editor. With the entity that you just created you can click the date cell you will see a pop up men which will show you the other possible attribute types.

Core Data Relationships

A relationship is the definition between two or more entities. For this example we will not be using relationships but for an example you want to define the relationship between an Employee and Employer. Relationships come in either a to-one or to-many type. This means for example that one Employer might many Employees and many Employees might have One Employer.

Core Data Fetched Properties

A fetched property is like adding in extra meta data. Lets say you wanted to add an employee start date attribute you would use a fetched property called employeeStartDate to get all the employees with the same start date.

Fetched Properties do not load along with an object like Relationships. For example if the employee had a relationship to the employer, when the instance of employee is called (loaded) the corresponding employer instance will be called also, however, when the employee is loaded, a fetched object of the above employee start date will not be evaluated.

Part 2

Go ahead and check out the second installment:

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly

Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.

Written by:

Nolan is a Mac OS X developer turned iOS engineer. At Twitter, formerly at Zappos and Cisco Systems. Married with two girls living in sunny Las Vegas.