loading...
Cover image for CRUD Operations with the Realm in Swift

CRUD Operations with the Realm in Swift

yusasarisoy profile image Yuşa Sarısoy ・5 min read

Hi, everyone. This is Yuşa and I am working at WeWALK as the iOS Developer. Unlike my previous posts, after that, I will share posts about iOS Development and Swift. This is my first article about iOS Development, so I am pretty excited to share it with you. In this article, we will try to find an answer to the following question: "How to use Realm in Swift?". If you follow me on GitHub, you surely know that I love open-source. And, in one of my open-source iOS projects, I started to use Realm instead of CoreData and loved it! I will show some code parts from the project where I use Realm and so, we will understand how to implement it to an existing project. In addition, you can also reach the open-source project using Realm at the end of the post! Great, isn't it? So, enough chit-chat! Let's knuckle down!

Firstly, let's understand the Realm and its context. In a nutshell, Realm is a mobile database that runs directly inside phones, tablets, or wearables and it's faster than even raw SQLite on common operations while maintaining an extremely rich feature set. 

We will use the Realm for CRUD operations. Create, Read, Update, and Delete respectively. You can implement the whole lines of code in the post for an existing project or a brand new project. The choice is yours!

...

Cocoapods and the Podfile

Alt Text

So, let's dive into the programming! The first job is creating the Podfile. Podfile is where we set up the libraries we want to use. To create Podfile, CocoaPods must have installed in your machine. CocoaPods manages library dependencies for your Xcode projects. It contains thousands of third-party libraries. If you have not CocoaPods, please run the following line in your terminal:

sudo gem install cocoapods

After we installed CocoaPods, we can switch to the project. Let's open the project in the terminal and write the following line to create our Podfile:

pod init

That line will create the Podfile, You can open the Podfile from the terminal writing the following line:

open Podfile -a Xcode

Uncomment the following line if it is not:

use_frameworks!

And add the following line to install the Realm to the project:

pod 'RealmSwift'

To install the Realm, use the following line:

pod install

When the installation completed, you will see that you have the Realm in your project. Also, that line will create a file with .xcworkspace extension. We will continue to work on the project using the .xcworkspace extension.

...

Importing the Realm

Alt Text

In my project, which is a to-do list application, I have two different model classes as the Category and the Item. Every item must have only one category and a category should be multiple items, one to many relationships between them. After this information, let's create these classes.

We import the Realm in a class using the following line in Swift:

import RealmSwift

We also create an object item in the Realm using the following line in Swift:

@objc dynamic var name: String = ""

The dynamic keyword might seems unfamiliar at first glance. But don't worry, I will explain why we use it. When we use the dynamic, you tell the compiler that dynamic dispatch should be used to access that member. That's the idea of the Realm: fast and dynamic reaction.

Alt Text

...

After an example, I will create my Category class:

import RealmSwift

class Category: Object {
    @objc dynamic var name: String = ""
    let items = List<Item>()
}

There is a generic type called List and it belongs to the Realm. Like Swift's List, List is a generic type that is parameterized on the type it stores. So, I store the Item data in Category. After that, I will create the other class, the Item class.

import RealmSwift

class Item: Object {
    @objc dynamic var title: String = ""
    @objc dynamic var done: Bool = false
    var parentCategory = LinkingObjects(fromType: Category.self, property: "items")
}

And there is another component that belongs to the Realm, the LinkingObjects. LinkingObjects is an auto-updating container type. It represents zero or more objects that are linked to its owning model object through a property relationship. With the LinkingObjects, we can create a relationship between the Category and the Item.

...

Create Operation with the Realm

Alt Text

To create a category using the Realm, firstly, we will import the Realm in where we will do the create operation. In my case, this will be the CategoryViewController.

import RealmSwift

And then, we will get the default Realm.

import RealmSwift

class CategoryViewController: UITableViewController {
    // Get the default Realm.
    let realm = try! Realm()

    ...

}

Now, we can use the Realm for the create operation. I have a function called save and it has one parameter: save(category: Category). It provides us to create a new category. In the do-catch block, we will do our Create operation.

func save(category: Category) {
    do {
        try realm.write {
            realm.add(category)
        }
    } catch {
        print("An error occurred while saving the category: \(error)")
    }


    tableView.reloadData()
}

...

Read Operation with the Realm

Alt Text

Using the objects function with Realm will be sufficient to read the categories we have created by writing a single line of code. It returns all objects of the given type stored in the Realm.

class CategoryViewController: UITableViewController {
    var categories: Results<Category>!
    ...

    func loadCategories() {
        // Read the categories.
        categories = realm.objects(Category.self)
        tableView.reloadData()
    }
}

...

Update Operation with the Realm

Alt Text

Alright, let's talk about updating the items. But how? In the project, each item has both the name and the status. This status is about whether the item has been done or not. We use the tick icon for check of this. We will update the item's status on UITableView. I will use ToDoListViewController.

class ToDoListViewController: UITableViewController {
    var todoItems: Results<Item>?
    ...

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if let item = todoItems?[indexPath.row] {
            do {
                try realm.write {
                    // Update the item's status.
                    item.done = !item.done
                }
            } catch {
                print("An error occurred while saving the status: \(error)")
            }
         }


        // Reload the table view after the check action.
        tableView.reloadData()


        // Deselect the selected row of the table view.
        tableView.deselectRow(at: indexPath, animated: true)
    }
    ... 
}

...

Delete Operation with the Realm

Alt Text

Delete operation is almost the same as the Update operation. The only difference is instead of checking, we use delete() function.

class ToDoListViewController: UITableViewController {
    var todoItems: Results<Item>?
    ...

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        // Update the item's status.
        if let item = todoItems?[indexPath.row] {
            do {
                try realm.write {
                    try realm.write {
                        // Delete an item.
                        realm.delete(item)
                    }
                }
            } catch {
                print("An error occurred while deleting the item: \(error)")
           }
        }
        // Reload the table view after the check action.
        tableView.reloadData()


        // Deselect the selected row of the table view.
        tableView.deselectRow(at: indexPath, animated: true)
    }
    ...
}

...

Conclusion

Alt Text

As a result, we found answers to such questions like "What is Realm and how is it used for CRUD operations?", "What is Cocoapods, how is it installed on the machine and used in the project?". As I said at the beginning of the article, I am sharing the project that I use the Realm. You can reach by clicking the following link: Listinn

I wish you all have a healthy day!

Posted on by:

yusasarisoy profile

Yuşa Sarısoy

@yusasarisoy

Not talented, just obsessed.

Discussion

pic
Editor guide