Mastering In CoreData (Part 3 Coding: CRUD in Core Data)

Core Data

In order to demonstrate basics of the Core Data, let’s create a single view iOS app with Use Core Data is selected or download the starter project.

Single View Application

If you have an existing project in which you don’t select Use Core Data checkbox, still you can add Core data and I will show that in later part. Once the project is created, you will see a file like CrudOperationCoreData.xcdatamodeld added.

I will be demonstrating CRUD operation on the Todo application. Final app can perform the following functions

  1. User can add task
  2. User can delete task
  3. User can see all the tasks

When you CrudOperationCoreData.xcdatamodeld file, 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.

Add Entity
Update Entity Name
Properties Added

What we have done so far we created a project with Core Data support. In CrudOperationCoreData.xcdatamodeld we define out Entity or table in database term and we define property (column in database term). “xcdatamodeld “ is a file called Managed object model where all schema of the application is defined as we discussed in the previous part. I said we will be calling Part 2 when we will go in depth since we talked much on theoretical aspects in that part.

Managed object model

A managed object model is a set of objects that together form a blueprint describing the managed objects you use in your application

Schema of the model objects you use in your application

Graphical Mode of Managed Object Model

As we discussed in Part 2 that we need to create Core Data stack in order to work with Core Data but we didn’t create stack yet. The truth is when we checked Use Core Data while creating a project it automatically created the stack code in AppDelegate file. Open AppDelegate file

Core Data Stack Code in AppDelegate File

When you see the code you hardly see anything you learned in the Core Data stack Part 2. But you can see the NSPersistentContainer lazy property

NSPersistentContainer

NSPersistentContainer simplifies the creation and management of the Core Data stack by handling the creation of the managed object model (NSManagedObjectModel), persistent store coordinator (NSPersistentStoreCoordinator), and the managed object context (NSManagedObjectContext). Available from iOS 10

When you jump to the NSPersistentContainer class definition you will see all the Core Data stack components present here.

Create Records Core Data

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

  • Refer to persistentContainer from appdelegate singleton object
  • Create/Access the singleton managed object context from persistentContainer
  • Create an entity with Task (represent ToDo task)
  • Create new record with this Task Entity
  • Set values for the records for each key
  • Save it to the disk (Persistent Store).

Before you save or retrieve anything from your Core Data store, you first need to get your hands on an NSManagedObjectContext. You can consider a managed object context as an in-memory “scratchpad” for working with managed objects.

Think of saving a new managed object to Core Data as a two-step process

  1. First you insert a new managed object(Task) into a managed object context
  2. One you’re happy, you commit the changes in your managed object context to save it to disk.

Xcode has already generated a managed object context as part of the new project’s template. Remember, this only happens if you check the Use Core Data checkbox at the beginning. This default managed object context lives as a singleton property of the NSPersistentContainer in the application delegate. To access it, you first get a reference to the app delegate.

Where data stored physically/disk

By default, Core Data stack uses SQLite as a persistent store in backend. You can see SQLite file generated in documents directory with .sqlite extension. Open this file in DB Browser For SQLite. You will see the data we just added and committed physically stored now. Save method moved all data from NSManagedObjectContext(memory) to persistent store (disk).

Now NSManagedObjectContext cached this data. Next time if you want to fetch this data it first check from cache (NSManagedObjectContext) if it found, it will return from cache else it will go to the persistent store which would take more time than fetching from cache.

Task object in Disk SQlite file

Fetch Record from Core Data

The process of fetching the records from Core Data has following tasks

  • Refer to persistentContainer from appdelegate singleton object
  • Create/Access the singleton managed object context from persistentContainer
  • Created a fetch request to filter only NSManagedObject having entity name Task.
  • You handed the fetch request to the managed object context to do the heavy lifting. fetch(_:) returns an array of managed objects meeting the criteria specified by the fetch request.
Fetch Task Object Core Data

NSFetchRequest

NSFetchRequest is used to retrieve data from a persistent store. We will look this in later part when we will be using NSFetchRequest in depth. Like save(), fetch(_:) can also throw an error so you have to use it within a do block. If an error occurred during the fetch, you can inspect the error inside the catch block and respond appropriately.

Build and run the application. Immediately, you would see in the console the save ToDo list task is shown

Delete Record from Core Data

The process of deleting the records from Core Data has following tasks

  • Refer to persistentContainer from appdelegate singleton object
  • Create/Access the singleton managed object context from persistentContainer. This application have one singleton managed object context that have initially the same data (replica in memory) of a persistent store and acts as a cache. You can do changes in that scratchpad and if you don’t need any changes you can do undo action to discard these changes and if you perform save operation it will dump managedObjectContext data into persistent store (disk).
  • Created a fetch request to filter only NSManagedObject having entity name Task.
  • Iterate over all objects and call delete method in the context. This step will delete the object in that context and persistent store have this object since we deleted from cache only.
  • Finally we commited changes to persistent store. Now both context and persistent store have same state. You can see from the sqlite file that no data is there as shown in Figure 3
Figure 3

Summary

We just finished CRUD operations coding part. In this part we used KVC to access an entity’s attributes rather than a more natural object-style way. As we said in part1.

A Core Data stores thing in a way that looks very object oriented to our code. Entity refer to Class, attributes refereed to var and relationship refer to var pointing to other class

What Next?

In the next part we will perform the CRUD operation in an object oriented way

Useful Links

https://store.raywenderlich.com/products/core-data-by-tutorials

https://www.objc.io/issues/4-core-data/core-data-overview/

https://en.wikipedia.org/wiki/Object-relational_mapping

https://cocoacasts.com/what-are-core-data-entities-and-attributes

https://cocoacasts.com/what-is-the-core-data-stack

https://developer.apple.com/library/archive/documentation/DataManagement/Devpedia-CoreData/coreDataStack.html

https://medium.com/@ankurvekariya/core-data-crud-with-swift-4-2-for-beginners-40efe4e7d1cc

https://www.raywenderlich.com/7569-getting-started-with-core-data-tutorial

https://developer.apple.com/library/archive/qa/qa1952/_index.html