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.

4.4 (23) · 1 Review

Download materials
Save for later
Share
You are currently viewing page 2 of 4 of this article. Click here to view the first page.

Adding Records

When the user adds a new specimen, they can enter the specimen name and select a category. Open CategoriesTableViewController.swift. This view controller presents the list of categories in a table view so the user can select one.

Before you start writing code to integrate Realm, you need to import the RealmSwift framework. Add the following line to the top of the file, below import UIKit:

import RealmSwift

You’ll populate this table view with some default categories. These Category instances can be stored in an instance of Results.

CategoriesTableViewController has a categories array as a placeholder for now. Find the following code at the top of the class definition:

var categories: [Any] = []

Replace that code with the following:

let realm = try! Realm()
lazy var categories: Results<Category> = { self.realm.objects(Category.self) }()

When you want to fetch objects, you always define the models you want. In the code above, you first create a Realm instance and then populate categories by calling objects(_:) on it, passing in the class name of the model type you want.

Note: To simplify the code required in this tutorial, you’re using try! when calling Realm methods that throw an error. In your own code, you should be using try and do / catch to catch and handle errors.

You want to give your user some default categories to choose from the first time the app runs.

Add the following helper method to the class definition:

private func populateDefaultCategories() {
  if categories.count == 0 { // 1
    try! realm.write() { // 2
      let defaultCategories =
        ["Birds", "Mammals", "Flora", "Reptiles", "Arachnids" ] // 3
      
      for category in defaultCategories { // 4
        let newCategory = Category()
        newCategory.name = category
        
        realm.add(newCategory)
      }
    }
    
    categories = realm.objects(Category.self) // 5
  }
}

Here’s what’s going on in each numbered line:

  1. If count is equal to 0 this means the database has no Category records. This is the case the first time you run the app.
  2. This starts a transaction on realm, and you’re now ready to add some records to the database.
  3. Here, you create the list of default category names and then iterate through them.
  4. For each category name, you create a new instance of Category, populate name and add the object to realm.
  5. You fetch all of the categories you created and store them in categories.

Add the following line to the end of viewDidLoad():

populateDefaultCategories()

This calls the helper method to populate your test categories when the view loads.

Now that you have some data, you’ll update the table view data source methods to show the categories. Find tableView(_:cellForRowAt:) and add the following before return cell:

let category = categories[indexPath.row]
cell.textLabel?.text = category.name

This implementation retrieves a category from categories based on the index path. It then sets the cell’s text label to show the category’s name.

Next, add this property below the other properties you added to CategoriesTableViewController:

var selectedCategory: Category!

You’ll use this property to store the currently selected Category.

Find tableView(_:willSelectRowAtIndexPath:) and add the following before return indexPath:

selectedCategory = categories[indexPath.row]

This stores the user’s selection in the property selectedCategory you declared above.

Build and run your app.

Adding a category

Zoom and pan the map to somewhere interesting and create a new annotation by tapping on the + button in the top-right. Tap on the map pin to select it, and then tap on the annotation data to edit the details. Finally, tap the Category text field to see the list of categories as shown below:

Category overview

You can select a category, but that only saves it to the property and not anywhere else in the database. It’s nice to see the categories show up in the app, but it’s always reassuring to see the records in the database. You can do this via the Realm Browser.

Introducing the Realm Browser

Realm includes the Realm Browser for reading and editing databases. The Realm database format is proprietary and not human-readable.

You can download the Realm Browser here.

Realm Browser

Working With Realm Browser

It’s important to know where your Realm database is stored while developing your app — and there’s a neat trick you can use to find out where it is.

Open MapViewController.swift and add the following line to the top of the file below the existing import statements:

import RealmSwift

Add the following line to viewDidLoad() after the call to super.viewDidLoad():

print(Realm.Configuration.defaultConfiguration.fileURL!)

This line prints the database location to the debug console. It’s a short step to then browse the database using the Realm Browser.

Build and run your app, and you’ll see that it reports the location of the database in the Xcode console.

The easiest way to go to the database location is to open Finder, press Shift-Command-G and paste in the path your app reported.

Once you open the folder in Finder, you might see one or two files. One of them is default.realm, which is your database file. The second file, that may or may not be present, is default.realm.lock. The lock file prevents modification from other apps while the database is in use.

If you haven’t yet downloaded the Realm Browser, download it from the App Store. Double-click default.realm to open it with Realm Browser:

Once the database is open in Realm Browser, you’ll see Category with a 5 next to it. This means that this class contains five records. Click a class to inspect the individual fields contained within.

Realm categories overview

Adding Categories

You can now put in place the logic to set the category of a Specimen.

Open AddNewEntryController.swift and import the RealmSwift framework below the existing import statements:

import RealmSwift

Add the following property to the class:

var selectedCategory: Category!

You’ll use this to store the selected Category.

Next, find unwindFromCategories(segue:) and add the following implementation inside:

if segue.identifier == "CategorySelectedSegue" {
  let categoriesController = segue.source as! CategoriesTableViewController
  selectedCategory = categoriesController.selectedCategory
  categoryTextField.text = selectedCategory.name
}

unwindFromCategories(segue:) is called when the user selects a category from CategoriesTableViewController that you set up in the previous step. Here, you retrieve the selected category, store it in selectedCategory and fill in the text field with the category’s name.

You can continue by creating your first Specimen!