Getting Started with Core Data

Tri Rejeki
GITS Apps Insight
Published in
5 min readMay 15, 2019
Photo by Samuel Zeller on Unsplash

Overview

Core Data is one of frameworks that is provided for iOS to manage the mapping of your objects to a storage.

The first step in working with Core Data is to create a data model file. Here you define the structure of your application’s objects, including their object types, properties, and relationships.

You can add a Core Data model file to your Xcode project when you create the project. Or you can add it to an existing project.

So, let’s get it started!

Core Data Creation

If you create a new project for the first time, you can use this way:

In the dialog for creating a new project, do not forget to select the Use Core Data checkbox.

New Project Option Dialog

For existing project, you can use this way: Choose File > New > File then this dialog will be showed.

New File Option Dialog

After naming your Core Data model, it will appear like this in your project:

Core Data Model

Data Model

In data model, there are some properties that help you to create your own database. You can see it in this picture below.

JSdb.xcdatamodeld Panel

Add Entity is to create some kind of table in your database.

Add Attribute is to add some attribute to your entities.

Editor Style is the UI that shows how your database look like. If grid style is selected, you can see every attribute type such as String, Int, Bool, or else.

For example, I will create JSdb. There are entities such Jadwal & Display Jadwal.

Jadwal Entity
Entities Editor

How to Store Data

Setup Your AppDelegate.swift

First, go to your AppDelegate.swift then add variables and functions like the example below.

The Directory that the Application Uses to Store the Core Data

// MARK: — Core Data stacklazy var applicationDocumentsDirectory: URL = {   let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)   return urls[urls.count-1]}()

The Managed Object Model for the Application

This property is mandatory. It is a fatal error for the application if cannot find and load its model.

lazy var managedObjectModel: NSManagedObjectModel = {   let modelURL = Bundle.main.url(forResource: “JSdb”, withExtension: “momd”)!   return NSManagedObjectModel(contentsOf: modelURL)!}()

The Persistent Store Coordinator for the Application

This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.

@available(iOS 10.0, *)lazy var persistentContainer: NSPersistentContainer = {   let container = NSPersistentContainer(name: “JSdb”)   container.loadPersistentStores(completionHandler: {  (storeDescription, error) in   if let error = error as NSError? {      fatalError(“Unresolved error \(error), \(error.userInfo)”)   }   })   return container}()lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {   // Create the coordinator and store   let coordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)   let url = applicationDocumentsDirectory.appendingPathComponent(“JSdb.sqlite”)   var failureReason = “There was an error creating or loading the application’s saved data.”   let options = [NSMigratePersistentStoresAutomaticallyOption: NSNumber(value: true as Bool), NSInferMappingModelAutomaticallyOption: NSNumber(value: true as Bool)]   do {      try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: options)   } catch {      // Report any error we got.      var dict = [String: AnyObject]()      dict[NSLocalizedDescriptionKey] = “Failed to initialize the application’s saved data” as AnyObject      dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject      dict[NSUnderlyingErrorKey] = error as NSErro      NSLog(“\(dict)”)      abort()   }   return coordinator}()

The Managed Object Context for the Application

This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.

This return managed object context for the application (which is already bound to the persistent store coordinator for the application).

lazy var managedObjectContext: NSManagedObjectContext? = {   let coordinator = persistentStoreCoordinator   var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)   managedObjectContext.persistentStoreCoordinator = coordinator   return managedObjectContext}()

Setup Your ViewController.swift

Next, we need to setup the ViewController file. You will need to implement this file to use Core Data. For example is ViewController.swift.

var context: NSManagedObjectContext?var appDelegate: AppDelegate?   override func viewDidLoad() {      super.viewDidLoad()      appDelegate = UIApplication.shared.delegate as! AppDelegate      //…
}
}

Here is the function to set value of context.

func getContext() {   if #available(iOS 10.0, *) {      self.context = appDelegate.persistentContainer.viewContext   } else {      self.context = appDelegate.managedObjectContext   }}

Now, you can call function getContext every time you need to create, update, or delete on your Core Data.

Entity Creation

First, we need to initialize model variable as Jadwal entity.

self.getContext()let model = NSEntityDescription.insertNewObject(forEntityName: “Jadwal”, into: self.context!) as! Jadwal

To set the value of attribute model you can simply use this:

model.id = Int16(1)model.subuh = “04:30”model.dzuhur = “11:49”model.ashar = “15:30”model.dhuha = “06:55”model.imsak = “04:20”model.maghrib = “17:59”model.place_id = “aXjdsakkjd12”model.isya = “19:00”model.terbit = “05:00”model.tanggal = “07–05–2019”

The model will automatically has attribute id, subuh, dzuhur, etc. from the attribute that is already created in Core Data model.

Next step is do store into database:

do {      try self.context?.save()      print(“Model Saved : \(model)”)} catch let error as NSError {      print(“Could not save. \(error), \(error.userInfo)”)}

That is all the basic about Core Data. Good luck and have fun with Core Data! :)

Reference

Tri Rejeki is an iOS Developer at GITS Indonesia who has been known as the mother for iOS team member at GITS. She has almost 10 years experience in the IT field on various roles such as Java Programmer and Android Developer.

--

--

GITS Apps Insight
GITS Apps Insight

Published in GITS Apps Insight

Journal about apps development for business and eCommerce from GITS Indonesia, a Google Certified Agency and Google Cloud Partner. | Website: gits.id

Tri Rejeki
Tri Rejeki

Written by Tri Rejeki

iOS Developer & Mobile Development Enthusiast