Start a Project

Introduction to Core Data

CoreData is the framework provided by Apple to save, track, filter, and modify the data within the iOS applications. It is not the database, but it uses SQLite as it’s persistent store. It is used to manage the model layer object in our application. It manages the object graphs, tracks the changes in the data, and modifies the data on the user interactions.

How to use Core Data

Let’s create a single view iOS application to demonstrate the basics of CoreData. To enable the app to use CoreData, we must check the Use CoreData option displayed at the bottom.

Checking the Use Core Data box will cause Xcode to generate boilerplate code for what’s known as an NSPersistentContainer in AppDelegate.swift.

The NSPersistentContainer consists of a set of objects that facilitate saving and retrieving information from Core Data. Inside this container is an object to manage the Core Data state as a whole, an object representing the Data Model, and so on.

the new file CoreData.xcdatamodeld has been added to the Application’s package. It acts as the model layer for the data. We can add the entity, attributes, and relations into the model layer.

Adding the Entity to Core Data Model

We can add an entity into the xcdatamodeld file by selecting an option Add Entity given at the bottom of the file. In the right pane of the file, we can add attributes, relationships, and fetched properties to the Entity.

Here, we have created a Student entity and added three attributes id, and name in the model, as shown in the below image.

Now, we have created our model Student. Let’s add some records into this model. The model will be saved to the CoreData.

To add records to the model, we need to follow the following steps.

We have created an AppDelegate object, the context, entity, and entity object. We have also set the values for the newly created entity object.

Now, we need to save the data inside CoreData. To save the data, we use the context object to save the context. We have to wrap this code with the try-catch block.

Now, if we run our application, our data will be saved inside the CoreData.

The AppDelegate.swift and ViewController.swift file contains the following code.

AppDelegate.swift

 

ViewController.swift

Fetching the records

Fetching the records from the CoreData is very simple. We need to instantitate the NSFetchRequest class and create a request object. We can pass this request object into the fetch() method for NSManagedContext reference.

 

Exit mobile version