Introducing Realm: Building Modern Swift Apps with Realm Database
Get started quickly with using Realm in your Swift apps with this free preview chapter from our new book: Realm: Building Modern Swift Apps with Realm Database! By Marin Todorov.
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
Introducing Realm: Building Modern Swift Apps with Realm Database
35 mins
This is an excerpt taken from Chapter 2, “Your First Realm App” of our book Realm: Building Modern Swift Apps with Realm Database. In the book, you’ll take a deep dive into the Realm Database, learn how to set up your first Realm database, see how to persist and read data, find out how to perform migrations and more. You’ll also take a look at the synchronization features of Realm Cloud to perform real-time sync of your data across all devices. Enjoy!
The idea of this chapter is to get you started with Realm without delving too much into the details of the APIs you’re going to use. This will hopefully inspire you to try and find the right APIs, figure out what they do, and perhaps even browse through RealmSwift’s source code.
Now you’ll take a leap of faith and dive right into creating an iOS app that uses Realm to persist data on disk while following this tutorial-style chapter.
Have no fear though, as the rest of this book will teach you just about everything there is to learn about Realm in detail. You’re going to learn the mechanics behind everything you’re about to do in this chapter and much, much more.
I invite you to work through this chapter’s exercises with an open mind. This chapter is simply about getting a feeling for using Realm in your Swift code.
Getting Started
The theme of to-do apps as an educational tool might be getting old by now, but the simple truth is that a to-do app does a great job of demonstrating how to build an app based on data persistence. A to-do app includes features like fetching a list of to-do items from disk, adding, modifying and deleting items, and using the data with some of the common UIKit components such as a table view, an alert view, buttons, and more.
In this chapter, you’re going to work on a to-do app that’s built on the Realm Database. This will be very useful as you learn the basics of CRUD operations with Realm.
To get started, open the macOS Terminal app (or another similar app of your choice), navigate to the current chapter’s starter project folder, run pod install
(as described in Chapter 1) and open the newly created Xcode workspace.
Open Main.storyboard to get an idea of the app’s basic structure:
The project consist of a single table view controller with a custom to-do item cell.
The source code structure follows a general pattern for all of the projects in this book:
-
The Classes folder is a catch-all location for code that doesn’t fall under one of the other folders mentioned below. In this project, it includes an extension on
UIViewController
to add a simple API to present alerts on screen, as well as a handy extension onUITableView
. - Assets is where you’ll find the app’s launch screen, meta information plist file, and the asset catalog.
- Scenes contains all of the app’s scenes; including their view controller, view and view model code, when available. In this project, you have a single view controller and a custom table cell class.
-
Entities contains the Realm object classes you’ll be persisting to disk. This is practically your data models, but backed by Realm. You have a single class called
ToDoItem
in this project. In later chapters, you’ll be working on more complex database schemas, but this simple schema will suffice for now.
The projects in this book all follow a similar code structure, but you aren’t forced to use this structure in your own work. We’ve provided it as a guideline so you’ll know where to look for files as later projects in this book become more complicated.
If you run the starter app right now, you’ll see that it compiles and displays an empty to-do list on screen:
Realm Objects
Realm objects are basically a standard data model, much like any other standard data model you’ve defined in your apps. The only difference is they’re backed by Realm persistence and abilities.
You won’t dive into Realm objects at this stage, as you’ll be going into more detail on how to define Realm models and persist them in the next section of this book. In this chapter, you’re going to waltz through these model definitions, and get straight into action.
In fact, the MyToDo starter project already includes a class that will serve as the data model for storing to-do items. Open Entities/ToDoItem.swift and notice the ToDoItem
class.
There are a few interesting points to note here, but you’ll be learning more about these subjects in the next chapters.
Dynamic Properties
First and foremost, you should recognize that the ToDoItem
class subclasses Object
. Object
is a base class all of your Realm-backed data entities must inherit from. This allows Realm to introspect them and persist them to disk.
Another interesting oddity in this class is that all of its properties are defined as dynamic
:
dynamic var id = UUID().uuidString
dynamic var text = ""
dynamic var isCompleted = false
This allows Realm to implement some custom, behind-the-scenes logic, to automatically map these properties to the data persisted to disk.
With the help of the dynamic
keyword, a model class serves as a loose proxy between your app’s code and the data stored on disk, as seen in this simple schema:
Primary Key
ToDoItem
also features a convenience init(_)
and overrides a static method called primaryKey()
from its parent class. Realm will call primaryKey()
to decide which property will be used as the object’s primary key.
The primary key stores unique values that are used to identify objects in the database. For example, if you’re storing Car
objects in the database, their uniquely identifying primary key can be their registration plate:
To make things easy, the id
property, which is the primary key of ToDoItem
, is automatically given a unique string UUID value. The UUID
Foundation class lets you easily generate unique identifiers like these:
DB4722D0-FF33-408D-B79F-6F5194EF018E
409BC9B9-3BD2-42F0-B59D-4A5318EB3195
D9B541AF-16BF-41AC-A9CF-F5F43E5B1D9B