Using SQLite in iOS app
In Software development, we need to persist the data in the application very often. However, we use data structures to manage and navigate data in the applications, but we may also need to store these structures for future use. In other words, data structures don't reside in the memory once the app gets killed. We have to save the data structures somewhere to access them whenever required.
There are various solutions to store the structured data in the database like SQLite, Realm, CoreData, etc. In this tutorial, we will discuss how we can store and manage the data in the SQLite database. However, if we have used CoreData before, we have already used SQLite since CoreData is just a layer on the top of SQLite. In this tutorial, we will perform the following database operations in the iOS application.
Let's create a single-view iOS application as SQLiteDemo to start with SQLite operations.
Once we are done creating the project, open the Main.storyboard file and add a table view to the View Controller as shown in the below image.
To use the table view, we also need to create its outlet in the ViewController.swift class. Once we implement the delegate and datasource methods, the ViewController.swift contains the following code.
Now, we will create a model class Employee. In our project, the Employee has the name, age, and id. For this purpose, create a new swift file and add the following code.
Now, we will create a class that contains the DB operations. We have named the class as DBManager. It includes the methods to create the database, create the table, insert in the table, read from the table, and performing the deletion. The DBManager contains the following code.
Finally, we need to save the data in db in the ViewController. For this purpose, we will use DBManager class to save and retrieve data. The ViewController.swift contains the following code.
The output is shown in the image below.