CRUD operations using Realm in Swift

Anjali Joshi
6 min readMar 28, 2021

Realm is a database which is used as an alternative to SQLite and Core Data framework. It is much simpler and reduces lines of code.

In this article, we will perform CRUD operations using Realm database by creating a simple iOS app.

Prerequisites: MacOS, XCode, CocoaPods/Carthage installed on your Mac machine.

Open XCode and create a new iOS -> Single View App project. Name it and save it in a desired location.

First of all, we will add RealmSwift to our project using Cocoapods/Carthage.

NOTE: If you do not have CocoaPods/Carthage installed on your machine, install any one of them by following these links:

CocoaPods: https://cocoapods.org/

Carthage: https://github.com/Carthage/Carthage#installing-carthage

In my project, I have added it using CocoaPods.Close your project and open Terminal. Navigate to your project folder and create a Podfile by typing the command:

pod init

Image of the Terminal

Go inside the folder of your project. You will find a Podfile created inside it. Open the Podfile and type the following line inside this file.

pod ‘RealmSwift’

Image of the Podfile

Now close the Podfile and in your terminal type the following command:

pod install

Image of the Terminal

This will install Realm in our project. On successful installation, you must get the following message on your Terminal.

Realm installed successfully

As mentioned in the Terminal, close your current project and open the .xcworkspace file. Here onwards, we will be creating our project in this file.

Now, let’s design the UI of our app. I am creating a Contact List app in which we can add, view, update and delete our contacts. Create UI as shown below. I have set the Style of UITableViewCell as Subtitle.

Press Ctrl button and clicking on the table view, drag the mouse upwards towards the yellow icon above ViewController until a black box appears. You can see the yellow icon in the above image. Click on delegate and dataSource.

If you see the white dots besides dataSource and delegate, then you have connected the tableview to them.

Setting DataSource and Delegate for tableview

Connect the outlets of the UI to the ViewController.swift file.

In the ViewController.swift file, add the line ‘import RealmSwift’ and create a new class of subclass Object as shown below.

import UIKit
import RealmSwift
class ContactList: Object{@objc dynamic var name : String = ""@objc dynamic var phoneNo : Int64 = 0@objc dynamic var email : String = ""}

Add UITableViewDelegate, UITableViewDataSource to the ViewController and add the following lines inside the ViewController class.

class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {@IBOutlet weak var tableView: UITableView!private let realm = try! Realm()private var contact = [ContactList]()override func viewDidLoad() {super.viewDidLoad()contact = realm.objects(ContactList.self).map({$0})}func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {<#code#>}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {<#code#>}@IBAction func btnAdd(_ sender: Any) {}}

Add the following code in the respective tableview functions.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {return contact.count}func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {let cell = tableView.dequeueReusableCell(withIdentifier: "contact",for: indexPath)cell.textLabel?.text = contact[indexPath.row].namereturn cell}

NOTE: I have set the identifier of the tableviewcell as ‘contact’.

Add Operation:

Now let’s create another View Controller which we will use to add the details of the contact.

Drag and drop a View Controller from the Object Library and create a new Cocoa Touch File with the subclass UIViewController. Also, assign the name of the file in the class in Identity Inspector. Refer the below screenshot for the same.

Add labels and text fields for Name,Phone Number and Email ID respectively.

Adding a new View Controller

Also, add a Storyboard ID to the new view controller in the Identity Inspector.

Assigning a Storyboard ID

Add the below code in the Add function in the ViewController.swift file.

@IBAction func btnAdd(_ sender: Any) {guard let vc = storyboard?.instantiateViewController(identifier: "NewContact") as? NewContactViewController else{return}vc.completionHandler = {[weak self] inself?.refresh()}vc.title = "New Contact"vc.navigationItem.largeTitleDisplayMode = .nevernavigationController?.pushViewController(vc, animated: true)}

Create a new function refresh() which will reload the data of tableview.

func refresh(){contact = realm.objects(ContactList.self).map({$0})tableView.reloadData()}

Now, go to NewContactViewController.swift file. Add the below code in this file.

import UIKitimport RealmSwiftclass NewContactViewController: UIViewController {@IBOutlet weak var txtEmail: UITextField!@IBOutlet weak var txtPhone: UITextField!@IBOutlet weak var txtName: UITextField!private let realm = try! Realm()public var completionHandler: (() -> Void)?
override func viewDidLoad() {super.viewDidLoad()navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Save", style: .done, target: self, action: #selector(btnSave))}@objc func btnSave(_ sender: Any) {let contactName = txtName.textlet phoneNo = String(txtPhone.text!)let email = txtEmail.text ?? ""realm.beginWrite()let newContact = ContactList()newContact.name = contactName!newContact.phoneNo = Int64(phoneNo)!newContact.email = emailrealm.add(newContact)try! realm.commitWrite()completionHandler?()navigationController?.popToRootViewController(animated: true)}}

In the above code, we have created a Save button on the navigation bar which will store the entered data in the Realm database.

Run the project and you must be able to add a new contact.

Edit and Update Operations:

Now, let’s add one more ViewController i.e EditViewController on Main.storyboard. We will use this View Controller to edit and update the data of the selected contact. Also, create a new Cocoa Touch File with the subclass UIViewController and assign the class in the Identity Inspector. Also assign a storyboard ID for this View Controller.

EditViewController

Design the UI as shown in the above image and connect the outlets to the EditViewController.swift file.

Add the below code in the EditViewController.swift file.

import UIKitimport RealmSwiftclass EditViewController: UIViewController {var contactDetails : ContactList?public var deletionHandler: (() -> Void)?private let realm = try! Realm()@IBOutlet weak var txtEmail: UITextField!@IBOutlet weak var txtPhone: UITextField!@IBOutlet weak var txtName: UITextField!
override func viewDidLoad() {super.viewDidLoad()txtName.text = contactDetails?.nametxtEmail.text = contactDetails?.emailtxtPhone.text = String(contactDetails!.phoneNo)}@IBAction func btnUpdate(_ sender: Any) {let updateContact = realm.objects(ContactList.self).filter("name = %@",contactDetails?.name)if let dataToBeUpdated = updateContact.first{try! realm.write{dataToBeUpdated.name = txtName.text!dataToBeUpdated.email = txtEmail.text ?? ""dataToBeUpdated.phoneNo = Int64(txtPhone.text!)!}}deletionHandler?()navigationController?.popToRootViewController(animated: true)}}

Now, go to ViewController.swift file and add the below function in the file.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {tableView.deselectRow(at: indexPath, animated: true)let item = contact[indexPath.row]guard let vc = storyboard?.instantiateViewController(identifier: "EditContact") as? EditViewController else {return}vc.contactDetails = itemvc.deletionHandler = {[weak self] inself?.refresh()}navigationItem.largeTitleDisplayMode = .nevernavigationController?.pushViewController(vc, animated: true)}

By adding the above codes, you will be able to perform Edit and Update operations. The didSelectRowAt tableview function contains the code which will navigate to the Edit Page on clicking on the tableview cell.

The btnUpdate function in the EditViewController.swift file contains the code to update the details of the contact.

Delete Operation:

Now let’s modify the UI Design in the EditViewController. Add a Delete button on the EditViewController and connect it to the EditViewController.swift file.

Paste the below code in the Delete function in EditViewController.swift file.

@IBAction func btnDelete(_ sender: Any) {guard let deleteContact = contactDetails else {return}realm.beginWrite()realm.delete(deleteContact)try! realm.commitWrite()deletionHandler?()navigationController?.popToRootViewController(animated: true)}

With this we have completed our project. Run the application and now, you must be able to perform all the CRUD operations.

--

--