Realm

One requirement almost every apps has, in one form or the other, is data persistence. Any app with a minimum complexity will probably need a database.

Apple provides us with Core Data, an object model layer framework that is as powerful as it is hard to master.

Today I’d like to introduce you to a Core Data alternative. Realm is a database designed for mobile devices, and with an open source driver thought for Swift.

Let me show you just enough code to get you interested in Realm.

How to define a simple model

Do you remember the model used in the examples from Alamofire and JSONCodable? A post resource has an id, a user id, a title, and a body. We can write it as a Realm object model like this:

class Post: Object {
  dynamic var id: String = NSUUID().UUIDString
  dynamic var userId: String = NSUUID().UUIDString
  dynamic var title: String = ""
  dynamic var body: String = ""
}

We can create an instance of Post like any other Swift class:

let post = Post()
post.title = "any title"
post.body = "once upon a time..."

How to persist and fetch data

Now that we have a post instance we can persist in it the realm database with this simple command:

do {
  let realm = try Realm()

  try realm.write {
    realm.add(post)
  }
} catch {
  // handle error somehow
}

Note that Realm() provides us with the default realm database interface, have a look at the documentation to see how to get a connection with other types of realms.

Also note how we need to try both the realm instantiation and write operation, I told you Realm embraces Swift, didn’t I? 😎

We can then query the database for posts with APIs like:

// all objecs
realm.objects(Post)

// sort based on a property
realm.objects(Post).sorted("title")

// sort based on a closure
realm.objects(Post).sort { postA, postB in
  // ...
}

// filter using a predicate
let predicate: NSPredicate = // ...
realm.objects(Post).filter(predicate)

A database wouldn’t be very useful without relationships though, let’s see how to describe relationships using Realm.

How to define relationships using Realm

Let use better modelling for our posts, and create a User entity. A user can have many posts, but a post can have only one user.

class User: Object {
  dynamic var id = NSUUID().UUIDString
  dynamic var username = ""

  let posts = List<Post>()
}

class Post: Object {
  dynamic var id: String = NSUUID().UUIDString
  dynamic var user: User?
  dynamic var title: String = ""
  dynamic var body: String = ""
}

You can set the post -> user relationship simply by assigning a value to the user property of the Post instance.

You can set the user -> posts relationship using the append method of the Relam List type:

user.posts.append(newPost)

Next Steps

As I’ve said at the beginning, the point of this tutorial was to show you enough code using Realm to get you curious. If I’ve succeeded in my intent and you want to know more head over to Realm Swift’s documentation and the project’s repo on GitHub. As usual you can checkout the example code used in this tutorial and experiment with it. Finally, if you are wondering how to unit tests code interfacing with Realm, I wrote a post about it on mokacoding.com.


That’s it for today. See you tomorrow with a forms building library. Subscribe to the email list to avoid missing out.

If you found this post useful and want to support the Advent Calendar please consider sharing it on your favourite social network. Thanks 🎅