Get a Quote


Getting started with Core Data Fundamentals

oneclick, administrator/ April 20, 2019 12:18 pm 242 Views

Core Data Fundamentals

In this article, we will discuss Core Data basics and how Core Data framework is used in our iOS/MacOS applications.

What is Core Data?

Core Data is an article chart and industriousness structure given by Apple in iOS and Mac OS.

Core Data is utilized to maintain the model layer object in our application. You can utilize Core Data as a system to track, save, change and filter the information inside iOS/Mac applications. However, Core Data isn’t a Database. Core Data is utilizing SQLite as it’s a constant store however the core information system itself isn’t the database. Core Data does substantially more than databases like dealing with the article diagrams, following the changes in the information and a lot more activities.

In this article, we will perceive how to embed, update and erase information utilizing the Core Data system. With Core Data, you can undoubtedly map objects in your applications to the table records in the database without even information of any SQL.

How Does Core Data vary from SQLite?

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

SQLite:

  • SQLite has Data Constraints feature.
  • Operates on data, stored on disk.
  • It can Drop table and Edit data without loading them in memory.
  • It is slow as compared to core data.

Core Data:

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

Getting Started with Tutorial

In order to understand the basics of the Core Data, let’s create a single view iOS app and select Core Data module.

Getting started with tutorial

We have created a demo project with Core Data Framework support. There are two notable changes in this Xcode template you can easily observe which are :

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

Core Data Stack

The Core Data Stack code is available inside the AppDelegate.swift file with clear documentation in the form of comments. In short, it set up the persistent container and save the data if there are any changes. As you know AppDelegate is the first file that executes as soon as app launched, we can save and fetch the context the form of Core Data Stack.

Data Model

The new CoreDataDemo.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.

Suppose we want to store the username, email and birth_date 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, email and birth_date as String type attributes. The end result will look like this.

Data Model

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

Add Records to Core Data

We need to follow below tasks in order to add data in Core Data.

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

First import CoreData to your ViewController.swift file.

Let’s start with Refer to persistentContainer which is already available in AppDelegate and Create Context:

let appDelegate = UIApplication.shared.delegate as! AppDelegate

let context = appDelegate.persistentContainer.viewContext

Now Create entity and Create new record in Core Data:

let entity = NSEntityDescription.entity(forEntityName: “Users”, in: context)

let newUser = NSManagedObject(entity: entity!, insertInto: context)

We need to add few data to our newly created records for each keys :

newUser.setValue(“Viral”, forKey: “username”)

newUser.setValue(“Viral123”, forKey: “password”)

Finally, we have set up all values, now save then inside the Core data. Already methods for saving the context exist in the AppDelegate.swift file 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 for handling the exception.

do {

try context.save()

} catch {

print(“Failed while saving”)

}

Fetch Records from Core Data

It’s also each to fetch saved data from Core Data. We need to follow the below tasks :

  • Need to prepare the request of type NSFetchRequest for the entity
  • Then fetch the result from the context in the form of an array of [NSManagedObject]
  • Finally, iterate through an array to get value for the specific key

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

let request = NSFetchRequest<NSFetchRequestResult>(entityName: “Users”)

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”)

}

Finally, you have fetched username from CoreData for each record.

What to do Next?

We have saved and retrieve data from Core data but these are basic operations to start with, we can do a lot more things with Core Data. We can modify, delete, tracking data changes, adding predicates. And it’s fun to do all these things with Core Data.

If you face any technical difficulties feel free to contact our technical experts, we would love to resolve your queries. You can contact us here.

Stay tuned for the next post.