Topics

#49: Realm Basics 🔮

Topics

Realm is a database made specifically for running on mobile devices. It works on Mac and iOS devices. (It even supports Android!) It's a great alternative to Core Data or even raw SQLite.

There's plenty to love about Realm, but the best part is it's ultra-simple API:

Define an Object

import RealmSwift

class Spaceship: Object {
  dynamic var name = ""
  dynamic var topSpeed = 0 // in km
}

Define a Related Object

class Spaceship: Object {
  dynamic var name = ""
  dynamic var topSpeed = 0
  dynamic var owner: User?
}

class User: Object {
  dynamic var firstName = ""
  dynamic var lastName = ""
  let spaceships = List<Spaceship>()
}

Create an Instance of an Object

var ship = Spaceship()

ship.name = "Outrider"
ship.topSpeed = 1150

var dash = User()

dash.firstName = "Dash"
dash.lastName = "Rendar"

ship.owner = dash

// need one Realm per thread
let realm = Realm()

realm.write {
  realm.add(ship)
}

Find Objects

Queries in Realm couldn't be simpler. They are chainable. You can add as many calls to .filter as you'd like. You can sort results using the chainable sorted function.

realm
  .objects(Spaceship)
  .filter("topSpeed > 1000")
  .filter("name BEGINSWITH 'O'")
  .sorted("topSpeed", ascending: false)

Performance

Realm uses a "zero-copy" design that allows it process > 35 queries a second, as well as insert > 95,000 records a second in a single transaction.

More info about Realm can be found at realm.io.