Skip to content
intermediate Phase 6 · Data Persistence

Realm

Use Realm for mobile data: object models, queries, reactive notifications, and sync.

50m
2 problems
Topic Progress 0%

Realm Setup & Models

What is Realm?

Realm is a mobile database that runs directly on devices. It's an alternative to Core Data and SwiftData, offering object-oriented storage with real-time notifications.

Installation

Add Realm via Swift Package Manager:

  • Repository: https://github.com/realm/realm-swift
  • Products: RealmSwift

Defining Models

import RealmSwift

class Task: Object {
    @Persisted var id: String = UUID().uuidString
    @Persisted var title: String
    @Persisted var isCompleted: Bool = false
    @Persisted var createdAt: Date = Date()
    @Persisted var priority: Int = 0
    
    override static func primaryKey() -> String? { "id" }
}

Realm Configuration

let config = Realm.Configuration(
    schemaVersion: 1,
    migrationBlock: { migration, oldSchemaVersion in
        if oldSchemaVersion < 1 {
            // migration logic
        }
    }
)

let realm = try! Realm(configuration: config)

Relationships

class Project: Object {
    @Persisted var name: String
    @Persisted var tasks: List<Task>
}

class Task: Object {
    @Persisted var project: LinkingObjects(fromType: Project.self, property: "tasks")
}

CRUD Operations

Create

try realm.write {
    let task = Task()
    task.title = "Buy groceries"
    realm.add(task)
}

Read

// All tasks
let allTasks = realm.objects(Task.self)

// Filtered
let pendingTasks = realm.objects(Task.self).where { $0.isCompleted == false }

// Sorted
let sorted = realm.objects(Task.self).sorted(byKeyPath: "createdAt", ascending: false)

Update

try realm.write {
    task.isCompleted = true
}

Delete

try realm.write {
    realm.delete(task)
}

// Delete all
try realm.write {
    realm.deleteAll()
}

Batch Operations

try realm.write {
    let pendingTasks = realm.objects(Task.self).where { $0.isCompleted == false }
    realm.delete(pendingTasks)
}

Reactive Notifications

Observation with notifications

Realm objects can be observed for changes:

let token = realm.objects(Task.self).observe { changes in
    switch changes {
    case .initial(let tasks):
        print("Initial: \(tasks.count) tasks")
    case .update(let tasks, let deletions, let insertions, let modifications):
        print("Updated: \(tasks.count) tasks")
    case .error(let error):
        print("Error: \(error)")
    }
}

SwiftUI Integration

@ObservedResults(Task.self) var tasks: Results<Task>

var body: some View {
    List {
        ForEach(tasks) { task in
            Text(task.title)
        }
    }
}

Write Transactions with Notifications

try realm.write {
    let task = Task()
    task.title = "New task"
    realm.add(task)
} // Notification fires after write completes

Stopping Observation

token.invalidate()  // Stop observing

Quiz

1. What macro is used for Realm model properties?

Question 1 options

2. How do you observe Realm object changes?

Question 2 options

3. What is the primary key in Realm?

Question 3 options

Flashcards

Question

What is Realm?

Answer

A mobile database that stores objects directly on device with real-time notifications and optional cloud sync.

Question

How do you write to Realm?

Answer

Wrap mutations in realm.write { } blocks. All changes are transactional.

Revision Notes

Key Takeaways

  • 1. Realm models extend Object class
  • 2. All writes must be in write transactions
  • 3. Realm provides reactive notifications
  • 4. ObservedResults works well with SwiftUI

Interview Tips

  • Compare Realm vs Core Data vs SwiftData
  • Explain Realm's zero-copy architecture
  • Discuss when to choose Realm over SQL-based solutions

Cheat Sheet

Realm = object database. Models extend Object. Use @Persisted for properties. Write in realm.write { }. Observe with .observe().