Categories: SwiftTutorials

Getting Started with Realm using Swift 3.0

Greetings Humans!

I was thinking for a long time to write about Realm. So…

What is Realm?

Realm is an open source client side database for Mobile platforms. Read more on their web page.

Its quite easy to use and less complicated as compared to Core Data. In this tutorial I am going to guide you through basic functions of it which are Add, Update and Delete.

Setting Up Project

Create a project and initiate a pod in it, then open the pod file and paste the following snippet in it.

target 'YourProjectName' do
 
  use_frameworks!

  pod ‘RealmSwift’

end
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end

After that save it and install the pod. It might take some time to install.

If you don’t want to use pod to install Realm, you can also download the required files and drag it in your project.

And your project is ready.

Constraining the View Controller

I have made a View Controller and created all the outlets and actions of the views on it.

 

Adding Model Class

Additionally, I also have created a Model class which in other words you can say table. With id as the primary key.

import UIKit
import RealmSwift

class Model: Object {
    
    dynamic var name : String?

    dynamic var id : String?
    
    
    
    override class func primaryKey() -> String? {
        return "id"
    }
}

 

Adding Object to Realm

Now, open your ViewController class and add two variables to it.

 var model : Model?
 let realm = try! Realm()

We are going to create a function to check if Realm already contains the primary key we are trying to add in.

func ifIdExists(findID: String) -> Model?{
     
     let predicate = NSPredicate(format: "id = %@", findID)
     let object = self.realm.objects(Model.self).filter(predicate).first
        if object?.id == findID {
        
        return object
            
        }
        return nil
    }

I have also created some helper functions.

    //Checks if both fields are empty
    func checkIfEmpty()-> Bool{
        if (nameTextField.text == "" ||  idTextField.text == ""){
        return false
        
        }
        return true
    
    }
   //Checks if Id field is empty
    func checkIfIdIsEmpty()-> Bool{
        if (idTextField.text == ""){
            return false
            
        }
        return true
        
    }

Finally, In action of your Done button. Every transaction (add, update or delete) in Realm needs to be done inside a write block. So first we initialized the object of Model class, then we passed data to the properties inside it and then added it to realm.

//Inside done button action
if checkIfEmpty(){
            //Initialize Model object
            self.model = Model()
            //Set properties in it
            model!.name = self.nameTextField.text!
            model!.id = self.idTextField.text!
            if let data = model{
                //Check if the entered 'id' is not already present
                if self.ifIdExists(findID: idTextField.text!) == nil {
                try! self.realm.write {
                  //Add object to Realm
                    self.realm.add(data)
                  //Refresh UI
                    self.tableView.reloadData()
                }
                }
            
            }  
        }

 

Updating Object in Realm

Updating procedure is somewhat similar to adding object, but first we search for the object we want to change and then update it. This code will go inside your Update button action.

//Inside Update button action
if checkIfEmpty(){
           //Check if object we want to change exists or not
            var object = self.ifIdExists(findID: self.idTextField.text!)
            if (object != nil){
           //If yes
                try! self.realm.write { 
            
                    self.model = Model()
                    //Update object
                    model!.name = self.nameTextField.text
                    //Leave the primary key same
                    model!.id = object!.id!
                    object = self.model
                    self.realm.add(object!, update: true)
                    self.tableView.reloadData()
                }
                
            }
            
        }

 

Deleting Object from Realm

Deleting is pretty straight forward. Check if the object exists in realm, then inside write block delete it from realm.

//Inside Delete button action
   if self.checkIfIdIsEmpty(){ 
            let objectToDelete = self.ifIdExists(findID: idTextField.text!)
            if objectToDelete != nil{
            try! realm.write{
                realm.delete(objectToDelete!)
                self.tableView.reloadData()
            }
        }

 

Displaying on TableView

In datasource functions of the tableview.

     func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        let model = self.realm.objects(Model.self)[indexPath.row]
        cell.textLabel!.text = model.name!
        cell.detailTextLabel!.text = "ID: \(model.id!)"
        
        return cell
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return realm.objects(Model.self).count
    }

 

Lastly, Build and run it. I got the following results.

The source code can be found here.
If you have any questions please leave a comment. 🙂

Good day!

Aaqib Hussain

Aaqib is an enthusiastic programmer with the love of Swift and anything that looks like Swift i.e Kotlin. He loves writing code in Swift, and exploring new technology and platforms. He likes to listen to old music. When he is not writing code, he's probably spend his time watching movies, tv-shows or anime, or either doing some research for writing the next article. He started Kode Snippets in 2015.

View Comments

  • Great Tutorial!
    I found many tutorial about using Realm but most of them is making simple ToDo app and just use the add object function. You have done good job.
    Beside, if I were you, I would code a little different in some points:
    1. No need to put conditions in brackets ()
    2. I avoid calling self if not necessary (only in closure and initialiser if needed)
    3. Function returns a boolean should be named started with "is", let say, in my code
    func isTextFieldEmpty() -> Bool {
    if nameTextField.text == "" || idTextField.text == "" {
    // And return TRUE if they are really empty (not false like yours)
    return true
    }
    return false
    }
    it's like normal English and we can call these condition by: if !isTextFieldEmpty {}
    4. In updateButtonTapped action, why we have to initialise an model object, then set its property according to object, then assign the object = model, then update the object to realm instead of doing like this:
    try! realm.write {
    object!.name = nameTextField.text
    realm.add(object!, update: true)

    Thanks

Recent Posts

Things to know when moving to Germany

This article covers some important things you must know when you are considering a move…

3 years ago

Unit Testing in Android for Dummies

What is Unit Testing? In its simplest term, unit testing is testing a small piece…

4 years ago

Factory Design Pattern

In this article, you will learn about a type of Creational Design Pattern which is…

5 years ago

Creating Target specific Theme in iOS

In this tutorial, you will go through the use of targets to achieve two separate…

5 years ago

Facade Design Pattern

In this article, you will learn about a type of Structural Design Pattern which is…

5 years ago

Singleton Design Pattern

In this article you will learn about a type of Creational Design Pattern which is…

5 years ago