Realm Tutorial: Getting Started
In this tutorial, you’ll learn how to use the Realm cross-platform mobile database solution by building an app that keeps track of wild animals. By Felipe Laso-Marsetti.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Realm Tutorial: Getting Started
30 mins
Realm is a cross-platform mobile database solution designed for mobile applications that you can integrate with your iOS projects. Unlike wrappers around Core Data, Realm doesn’t rely on Core Data or even an SQLite back end.
This tutorial introduces you to the basic features of Realm on iOS. By the end of this tutorial, you’ll know how to link the Realm framework, create models, perform queries and update records.
Getting Started
Use the Download Materials button at the top or bottom of this tutorial to download the starter project.
Here’s the scenario: You’ve accepted a position as an intern in the National Park Service. Your job is to document the species found in the largest national parks in the United States.
You’ll need an assistant to keep notes of your findings, but since the agency doesn’t have the budget to hire a new one, you decide to create a virtual assistant for yourself: an app named Agents Partner.
Open the starter project in Xcode. Currently, the app contains only the map functionality using MapKit, which is already set up in the project.
The starter project is missing Realm, so it’s time to add it.
An efficient way to install Realm is with CocoaPods.
In the root directory of the starter project, create a new file named Podfile. Copy the following text and paste it into the newly created file:
platform :ios, '12.0'
use_frameworks!
target 'Agents Partner' do
pod 'RealmSwift'
end
Save and close the file.
In Terminal and in the root directory of your project, run the following command:
pod install
This tells CocoaPods to scan through your Podfile and install any pods that you have listed in the file. Pretty neat!
It may take a bit for Realm to install, so keep an eye on your terminal. Once it’s complete, you’ll see a line near the bottom that begins with Pod installation complete!
.
In Finder, open the root directory of the starter project. Notice the folders that CocoaPods added as well as Agents Partner.xcworkspace.
If you have the starter project open in Xcode, close it now and open .xcworkspace by double-clicking the file. This file is what you need to open when you want to work on the project.
You just set up Realm using CocoaPods. Build and run the project to ensure everything compiles. If everything went as expected, you’ll see this:
Concepts and Classes Overview
To better understand what Realm does, here are some concepts and information about the classes you’ll use in this tutorial:
-
Realm: Realm instances are the heart of the framework. It’s your access point to the underlying database like a Core Data managed object context. You create instances using the
Realm()
initializer. -
Object: This is your Realm model. The act of creating a model defines the schema of the database. To create a model, you subclass
Object
and define the fields you want to persist as properties. -
Relationships: You create one-to-many relationships between objects by declaring a property of the type of the
Object
to which you want to refer. You can create many-to-one and many-to-many relationships via a property of typeList
. -
Write Transactions: Any operations in the database, like creating, editing or deleting objects, must be performed within writes by calling
write(_:)
onRealm
instances. -
Queries: To retrieve objects from the database you use queries. The simplest form of a query is calling
objects()
on aRealm
instance and passing in the class of theObject
you’re looking for. If your data retrieval needs are more complex, you can make use of predicates, chain your queries and order your results. -
Results: Results is an auto-updating container type that you get back from object queries. They have many similarities with regular
Arrays
including the subscript syntax.
With a brief introduction to Realm, it’s time to get your feet wet and build the rest of the project.
Your First Model
Open Specimen.swift from the Models group and add the following implementation:
import Foundation
import RealmSwift
class Specimen: Object {
@objc dynamic var name = ""
@objc dynamic var specimenDescription = ""
@objc dynamic var latitude = 0.0
@objc dynamic var longitude = 0.0
@objc dynamic var created = Date()
}
The code above adds a few properties:
name
and specimenDescription
store the specimen’s name and description. Specific data types in Realm, such as strings, must be initialized with a value. In this case, you initialize them with an empty string.
latitude
and longitude
store the coordinates for the specimen. Here, you set the type to Double
and initialize them with 0.0
.
created
stores the creation date of the specimen. Date()
returns the current date so the property is initialized with that value.
With your first model created in Realm, are you ready to use this knowledge in a small challenge?
Specimens should be separated into different categories. The challenge is to create a Category
model by yourself. Name the file Category.swift and give your new model a single String
property named name
.
If you want to check your work, the solution is below:
[spoiler title=”Category object”]
Category.swift will look like this:
import Foundation
import RealmSwift
class Category: Object {
@objc dynamic var name = ""
}
[/spoiler]
You have a Category
model that you somehow need to relate to the Specimen
model.
Recall the note above that stated you could create relationships between models by declaring a property with the appropriate model to be linked.
Open Specimen.swift and add the following declaration below the other properties:
@objc dynamic var category: Category!
This sets up a one-to-many relationship between Specimen
and Category
. This means each Specimen
can belong to only one Category
, but each Category
can have many Specimen
s.
You now have your basic data models in place. It’s time to add some records to your database!