Navigation

Quick Start - iOS SDK

Before you begin, ensure you have Installed the iOS SDK.

Note
This Quickstart is Local-only

For a quickstart featuring communicating with a backend Realm app over the network using Sync, Realm Functions, or user management, see the Quick Start with Sync, or the full iOS Tutorial.

Near the top of any Swift file that uses Realm, add the following import statement:

import RealmSwift

For a local-only Realm Database you can define your object model directly in code.

// LocalOnlyQsTask is the Task model for this QuickStart
class LocalOnlyQsTask: Object {
@objc dynamic var name: String = ""
@objc dynamic var owner: String?
@objc dynamic var status: String = ""
convenience init(name: String) {
self.init()
self.name = name
}
}

In a local-only Realm Database, the simplest option to open a realm is by omitting the configuration parameter, which uses the default realm:

// Open the local-only default realm
let localRealm = try! Realm()

You can also specify a Realm.Configuration parameter to open a realm at a specific file URL, in-memory, or with a subset of classes.

Tip

Once you have opened a realm, you can modify it and its objects in a write transaction block.

To create a new Task, instantiate the Task class and add it to the realm in a write block:

// Add some tasks
let task = LocalOnlyQsTask(name: "Do laundry")
try! localRealm.write {
localRealm.add(task)
}

You can retrieve a live collection of all tasks in the realm:

// Get all tasks in the realm
let tasks = localRealm.objects(LocalOnlyQsTask.self)

You can also filter that collection using a filter:

// You can also filter a collection
let tasksThatBeginWithA = tasks.filter("name beginsWith 'A'")
print("A list of all tasks that begin with A: \(tasksThatBeginWithA)")

To modify a task, update its properties in a write transaction block:

// All modifications to a realm must happen in a write block.
let taskToUpdate = tasks[0]
try! localRealm.write {
taskToUpdate.status = "InProgress"
}

Finally, you can delete a task:

// All modifications to a realm must happen in a write block.
let taskToDelete = tasks[0]
try! localRealm.write {
// Delete the LocalOnlyQsTask.
localRealm.delete(taskToDelete)
}

You can watch a realm, collection, or object for changes with the observe method.

Note

Be sure to retain the notification token returned by observe as long as you want to continue observing. When you are done observing, invalidate the token to free the resources.

// Retain notificationToken as long as you want to observe
let notificationToken = tasks.observe { (changes) in
switch changes {
case .initial: break
// Results are now populated and can be accessed without blocking the UI
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed.
print("Deleted indices: ", deletions)
print("Inserted indices: ", insertions)
print("Modified modifications: ", modifications)
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}

Later, when done observing:

// Invalidate notification tokens when done observing
notificationToken.invalidate()

Run the complete example by calling runLocalOnlyExample().

import RealmSwift
// LocalOnlyQsTask is the Task model for this QuickStart
class LocalOnlyQsTask: Object {
@objc dynamic var name: String = ""
@objc dynamic var owner: String?
@objc dynamic var status: String = ""
convenience init(name: String) {
self.init()
self.name = name
}
}
// Entrypoint. Call this to run the example.
func runLocalOnlyExample() {
// Open the local-only default realm
let localRealm = try! Realm()
// Get all tasks in the realm
let tasks = localRealm.objects(LocalOnlyQsTask.self)
// Retain notificationToken as long as you want to observe
let notificationToken = tasks.observe { (changes) in
switch changes {
case .initial: break
// Results are now populated and can be accessed without blocking the UI
case .update(_, let deletions, let insertions, let modifications):
// Query results have changed.
print("Deleted indices: ", deletions)
print("Inserted indices: ", insertions)
print("Modified modifications: ", modifications)
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
}
// Delete all from the realm
try! localRealm.write {
localRealm.deleteAll()
}
// Add some tasks
let task = LocalOnlyQsTask(name: "Do laundry")
try! localRealm.write {
localRealm.add(task)
}
let anotherTask = LocalOnlyQsTask(name: "App design")
try! localRealm.write {
localRealm.add(anotherTask)
}
// You can also filter a collection
let tasksThatBeginWithA = tasks.filter("name beginsWith 'A'")
print("A list of all tasks that begin with A: \(tasksThatBeginWithA)")
// All modifications to a realm must happen in a write block.
let taskToUpdate = tasks[0]
try! localRealm.write {
taskToUpdate.status = "InProgress"
}
let tasksInProgress = tasks.filter("status = %@", "InProgress")
print("A list of all tasks in progress: \(tasksInProgress)")
// All modifications to a realm must happen in a write block.
let taskToDelete = tasks[0]
try! localRealm.write {
// Delete the LocalOnlyQsTask.
localRealm.delete(taskToDelete)
}
print("A list of all tasks after deleting one: \(tasks)")
// Invalidate notification tokens when done observing
notificationToken.invalidate()
}
Give Feedback

On this page