Realm Tutorial: Getting Started

Learn how to use Realm, a popular cross-platform mobile database that is an alternative to Core Data. By Bradley Johnson.

Leave a rating/review
Save for later
Share

Update note: This tutorial was updated for iOS 9 and Swift 2.2 by Bradley Johnson. Original tutorial was by team member Bill Kastanakis.

Realm is a cross-platform mobile database solution designed specifically for mobile applications.

It’s fast, lightweight, and extremely simple to integrate in your project. Most common functions such as querying the database consist of a single line of code!

Unlike wrappers around Core Data such as MagicalRecord, Realm does not rely on Core Data or even a SQLite backend. The Realm developers claim that their proprietary data storage solution is even faster than SQLite and Core Data.

Here’s some example Core Data code to fetch a set of records with a predicate and then sort the results:

let fetchRequest = NSFetchRequest(entityName: "Specimen")
let predicate = NSPredicate(format: "name BEGINSWITH [c]%@", searchString)
fetchRequest.predicate = predicate
let sortDescriptor = NSSortDescriptor(key: "name", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]

do {
  let results = try managedObjectContext?.executeFetchRequest(fetchRequest)
} catch { ... }

What takes quite a few lines with Core Data can be achieved with far fewer lines in Realm:

let predicate = NSPredicate(format: "name BEGINSWITH [c]%@", searchString);

do {
  let specimens = try Realm().objects(Specimen).filter(predicate).sorted("name", ascending: true)
} catch { ... }

Working with Realm results in more concise code — which makes it easier to write and read your code.

This Realm tutorial will introduce you to the basic features of Realm on iOS. You’ll learn how to link in the Realm framework, create models, perform queries, and update records.

Getting Started

Here’s the scenario: you’ve accepted a position as an intern in the National Park Service and your job is to document the species found in the biggest national parks in the United States. You need an assistant to keep notes and document your findings, but the agency doesn’t have an assistant to spare, nor the budget to hire a new one. Instead, you’ll create a virtual assistant for yourself — an app named “Agents Partner”.

Download the starter project for this tutorial here: AgentsPartner_Starter

Open the starter project in Xcode. MapKit is already set up in your project. Right now your app only contains instances of UITableView and MKMapView to provide the map functionality.

Note: If you’re interested in learning more about MapKit, check out our MapKit: Getting Started tutorial, which provides an in-depth look at how to work with MapKit.

The starter project is missing Realm, so it’s time to add it.

Note:This tutorial was written against Realm 0.98.0.

One great way to install Realm is with CocoaPods. CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects, and it has thousands of libraries you can download and use in your own projects.

Note:If you are not familiar with CocoaPods or need help installing it, check out our very own CocoaPods tutorial.

Create a file called ‘Podfile’ in the root directory of the starter project (To do this in command line simply use the command touch Podfile). Copy the following chunk of text and paste it into your Podfile:

platform :ios, ‘9.0’
use_frameworks!

target ‘Agents Partner’ do
pod 'RealmSwift', '~> 0.98'
end

Save and close your Podfile. Back in the command line, in the root directory of your project (the same location your Podfile is in), run the command pod install. This tells CocoaPods to scan through your Podfile and install any pods you have listed in your Podfile. Pretty neat! It may take several minutes for Realm to install, keep an eye on your terminal and once it’s complete you will see a line near the bottom that begins with Pod installation complete!.

Open the root directory of the starter project in finder, and you will now see some folders that CocoaPods placed there, in addition to Agents Partner.xcworkspace. If you currently have your Agents Partner starter project open in Xcode, close it now, and then double click to open the .xcworkspace file. This is now the file you will open when you want to work on this project. If you open the regular project file by mistake, Xcode won’t properly be able to find any of the dependencies you installed with CocoaPods, so you must use the .xcworkspace file instead. Expand the Agents Partner project in the Project navigator, and then the group/folder also named Agents Partner to reveal the files you will be working with.

Thats it! Build and run the project to ensure everything compiles. If not, re-check the steps above carefully. You should see a basic screen like so:

Realm starter screenshot

Introducing Realm Browser

Realm also provides a nice utility that you’ll want to install from the App Store to make your life a little easier.

The Realm Browser lets you read and edit Realm databases. It’s really useful while developing as the Realm database format is proprietary and not easily human-readable. Download it here.

realm-browser

Concepts and Major Classes

In order to better understand what Realm does, here’s an overview of the Realm classes and concepts you’ll use in this tutorial:

Realm: Realm instances are the heart of the framework; it’s your access point to the underlying database, similar to a Core Data managed object context. You will 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 simply subclass Object and define the fields you want to persist as properties.

Relationships: You create one-to-many relationships between objects by simply declaring a property of the type of the Object you want to refer to. You can create many-to-one and many-to-many relationships via a property of type List, which leads you to…

Write Transactions: Any operations in the database such as creating, editing, or deleting objects must be performed within writes which are done by calling write(_:) on Realm instances.

Queries: To retrieve objects from the database you’ll need to use queries. The simplest form of a query is calling objects() on a Realm instance, passing in the class of the Object you are looking for. If your data retrieval needs are more complex you can make use of predicates, chain your queries, and order your results as well.

Results: Results is an auto updating container type that you get back from object queries. They have a lot of similarities with regular Arrays, including the subscript syntax for grabbing an item at an index.

Now that you’ve had an introduction to Realm, it’s time to get your feet wet and build the rest of the project for this tutorial.

Bradley Johnson

Contributors

Bradley Johnson

Author

Over 300 content creators. Join our team.