DEV Community

Alvar Arias
Alvar Arias

Posted on

Core Data in SwiftUI simple example

This is a very simple example of how to add Core Data to a project in SwiftUI.

To add Core Data to a project we need to follow these steps:

1 Create a Data model first, we insert a Data Model type file:

Image description

Then we assign a name to the file, in this case, “ModelApp” and by pressing the “Add Entity” button ” we create an entity (object inside the model).

Image description

2 We create the "DataController" class in charge of managing Core Data within our application. For this we insert the "DataController.swift" file and write the following:

Image description

3 We add the data controller to our project.
For this, we go to the initial file of our project, in this case, I open the file: "CoreDataEjemploApp.swift"

First I create a variable of type @StateObject, called "dataController" which is of type "DataController()" (the class we had defined above)

Image description

Then we add to the initial View in this case “ContentView” the variable “dataController” as a variable of type “environment” and this will be available to our View and the remaining Views through the viewContext() method.

We already have Data Core configured in our project, now we are going to read and add data that we will save persistently using our model.

Reading and writing data to Core Data

4.1 To read data to Core Data in the ContentView.Swift file, we write the following line:

Image description

Where @Fetch request is the property that allows us to create a variable called “products” that is the result of fetch data from the entity "Product" under a certain criterion in this case we request all the data using "sortDescriptors: []".

4.2.To write data to Core Data in the ContentView.Swift file, we write the following line:

Image description

Then we create a listView to display the data we have read from Core Data.

Image description

In addition to an "Add" button that adds data to our container.

Finally, we use try to save the information we have generated:

Image description

The final file looks like this:

Image description

We try clicking the "Add" button and we will randomly fill data with different names for our products.

You can stop the app and reload it and you will see that the data has been permanently recorded.

Conclusion:

This is a very simple project to see how Core Data works in SwiftUI, I hope I have motivated you to investigate more and use this excellent tool that we have to permanently save data in our applications, with the great advantage of not having to add external libraries and not grow the size of our App excessively.

You can download the project here

Top comments (0)