Core Data with Swift 4 for Beginners

Shashikant Jagtap
XCBlog
Published in
4 min readOct 23, 2017

Core Data is one of the most popular frameworks provided by Apple for iOS and macOS apps. Core data is used to manage the model layer object in our application. You can treat Core Data as a framework to save, track, modify and filter the data within iOS apps, however, Core Data is not a Database. Core Data is using SQLite as it’s persistent store but the framework itself is not the database. Core Data does much more than databases like managing the object graphs, tracking the changes in the data and many more things. In this short post, we will see how to save and retrieve data using Core Data frameworks.

Core Data Demo

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

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 fileCoreDataDemo.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.

Data Model

The new fileCoreDataDemo.xcdatamodeld acts as the model layer for the data that we want to save. We can easily ad the entity, attributes and relationships from the UI as like any other relational database.

Now that, let’s say we want to store the username, password and age attributes for the User entity. Select the CoreDataDemo.xcdatamodeld file and click on “Add Entity” (+) button and name the entity as Users. From the add username, password and age as String type attributes. The end result will look like this

Now that, we have modelled our data in the Users entity. It’s time to add some records and save it into the CoreData

Add Records to Core Data

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

  • Refer to persistentContainer
  • Create the context
  • Create an entity
  • Create new record
  • Set values for the records for each key

Let’s do everything inside theViewController.swift and viewDidLoad() method. As we know that container is set up in the AppDelegates so we need to refer that container.

let appDelegate = UIApplication.shared.delegate as! AppDelegate

We need to create a context from this container.

let context = appDelegate.persistentContainer.viewContext

Now let’s create an entity and new user records.

let entity = NSEntityDescription.entity(forEntityName: "Users", in: context)
let newUser = NSManagedObject(entity: entity!, insertInto: context)

At last, we need to add some data to our newly created record for each keys using

newUser.setValue("Shashikant", forKey: "username")
newUser.setValue("1234", forKey: "password")
newUser.setValue("1", forKey: "age")

Now we have set all the values. The next step is to save them inside the Core Data

Save the Data

The methods for saving the context already exist in the AppDelegate but we can explicitly add this code to save the context in the Database. Note that, we have to wrap this with do try and catch block.

do {          
try context.save()
} catch {
print("Failed saving")
}

At this stage, whenever we run our app the new entries will be added to the Core Data records.

Fetch from Core Data

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

  • Prepare the request of type NSFetchRequest for the entity
  • 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.

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Users")
//request.predicate = NSPredicate(format: "age = %@", "12")
request.returnsObjectsAsFaults = false
do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "username") as! String)
}

} catch {

print("Failed")
}

This will print the value of username from the Core Data. That’s it! Now that, you have successfully saved and fetched data from Core Data.

What Next?

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

Source Code

The source code for this demo app is on Github as CoreDataDemo repository. You can clone the repo and play with Core Data.

$ git clone git@github.com:Shashikant86/CoreDataDemo.git
$ cd CoreDataDemo
$ open CoreDataDemo.xcodeproj/

Have Fun with Core Data!

Like this post from XCBlog By XCTEQ ? You may also like some of our services like guest blogging or Mobile DevOps(CI/CD) or Test Automation. Chekout our services, open source projects on Github or Follow us on Twitter , Facebook, Youtube , LinkedIn. Download Our XCBlog iOS App to read the blogs offline.

XCTEQ Limited: Mobile DevOps, CI/CD and Automation

XCTEQ is a company specialised in Mobile DevOps, CI/CD, Mobile, AI/ML based Test Automation Checkout XCTEQ products and services at http://www.xcteq.co.uk or write to us on info@xcteq.co.uk..

--

--

Shashikant Jagtap
XCBlog

All the posts published on this channel before I joined Apple. Thanks for being a reader of XCBlog. Web: shashikantjatap.net, xcteq.co.uk