top of page

Using Realm database in iOS Swift Apps


Using Realm database in iOS Swift Apps

Realm is a popular mobile database solution that provides an alternative to traditional SQLite databases in iOS apps. It offers a simple and efficient way to persist data locally on the device and perform complex queries and transactions.


In this blog, we will explore how to integrate and use Realm in iOS apps to manage data storage and retrieval.


Prerequisites


To follow along with this tutorial, you should have a basic understanding of iOS app development using Swift and Xcode. Additionally, ensure that you have Xcode installed on your development machine.


Step 1: Installing Realm


To start using Realm in your iOS app, you need to install the RealmSwift library. There are multiple ways to install Realm, but the recommended method is using CocoaPods, a dependency manager for iOS projects.


Follow these steps to install Realm using CocoaPods:


1. Open Terminal and navigate to your project directory.


2. If you haven't already initialized your project with CocoaPods, run the command: pod init. This will create a Podfile for your project.


3. Open the Podfile using a text editor and add the following line inside the target block:

pod 'RealmSwift'

4. Save the Podfile and run the command: pod install in Terminal.


5. Wait for CocoaPods to download and install the RealmSwift library. Once completed, close your Xcode project and open the newly generated .xcworkspace file.


Step 2: Setting up Realm in your project


After installing Realm, you need to configure it in your iOS project. Follow these steps to set up Realm in your app:


1. In Xcode, open your project's .xcworkspace file.


2. Create a new Swift file (e.g., RealmManager.swift) to manage your Realm configuration and interactions.


3. Import the RealmSwift library at the top of the file:

import RealmSwift

4. Declare a class named RealmManager and add the following code:

final class RealmManager {
    static let shared = RealmManager() // Singleton instance
    private let realm: Realm
    private init() {
        // Get the default Realm configuration
        guard let realm = try? Realm() else {
            fatalError("Failed to initialize Realm")
        }
        self.realm = realm
    }
}

Step 3: Creating a Realm Object


In Realm, data is organized into objects, similar to tables in a traditional database. Each Realm object represents a row in the database table.


Follow these steps to create a Realm object in your iOS app:


1. Create a new Swift file (e.g., Task.swift) to define your Realm object.


2. Import the RealmSwift library at the top of the file:

import RealmSwift

3. Declare a new class and inherit from the Object class provided by Realm:

final class Task: Object {
    @Persisted(primaryKey: true) var id: ObjectId // Primary key
    @Persisted var name: String = ""
    @Persisted var dueDate: Date?
}

4. Customize the properties and their types according to your app's requirements. The @Persisted attribute marks a property for persistence in the Realm database.


Step 4: Performing CRUD Operations


Now that you have set up Realm and defined a Realm object, you can perform CRUD (Create, Read, Update, Delete) operations on your data. Follow these steps to perform basic CRUD operations:


1. To add a new object to the Realm database, use the following code:

let task = Task()
task.name = "Sample Task"
task.dueDate = Date()

try? RealmManager.shared.realm.write {
    RealmManager.shared.realm.add(task)
}

2. To fetch all objects of a specific type, use the following code:

let tasks = RealmManager.shared.realm.objects(Task.self)
for task in tasks {
    print("Task Name: \(task.name)")
    print("Due Date: \(task.dueDate ?? "")")
}

3. To fetch an object by its id, use the following code:

func fetchTaskById(id: ObjectId) -> Task? {
    return RealmManager.shared.realm
      .object(ofType: Task.self, forPrimaryKey: id)
}

4. To fetch objects by name, use the following code:

func fetchTasksByName(name: String) -> Results<Task>? {
    let predicate = NSPredicate(format: "name == %@", name
    return RealmManager.shared.realm
      .objects(Task.self).filter(predicate)
}

5. To update an existing object, modify its properties and save the changes:

if let task = tasks.first {
    try? RealmManager.shared.realm.write {
        task.name = "Updated Task"
    }
}

6. To delete an object from the Realm database, use the following code:

if let task = tasks.first {
    try? RealmManager.shared.realm.write {
        RealmManager.shared.realm.delete(task)
    }
}

Step 5: Advanced Realm Features


Realm offers additional features to handle more complex scenarios. Here are a few examples:


1. Relationships: You can establish relationships between Realm objects using properties like LinkingObjects or RealmOptional. Refer to the Realm documentation for detailed examples.


2. Queries: Realm provides a powerful query API to fetch objects based on specific criteria. For example:

let overdueTasks = RealmManager.shared.realm.objects(Task.self).filter("dueDate < %@", Date())

3. Notifications: You can observe changes in Realm objects using notifications. This allows your app to stay updated with real-time changes made by other parts of the app or remote data sources. Refer to the Realm documentation for more information.


Conclusion


In this blog, we explored the basics of using Realm in iOS apps. We learned how to install Realm, set it up in our project, create Realm objects, and perform CRUD operations. We also briefly touched upon advanced features such as relationships, queries, and notifications.


Realm provides a robust and efficient solution for data persistence in iOS apps, offering a wide range of features to simplify database management. Feel free to explore the Realm documentation for more in-depth usage and examples.


Happy coding !

Blog for Mobile App Developers, Testers and App Owners

 

This blog is from Finotes Team. Finotes is a lightweight mobile APM and bug detection tool for iOS and Android apps.

In this blog we talk about iOS and Android app development technologies, languages and frameworks like Java, Kotlin, Swift, Objective-C, Dart and Flutter that are used to build mobile apps. Read articles from Finotes team about good programming and software engineering practices, testing and QA practices, performance issues and bugs, concepts and techniques. 

bottom of page