2. OVERVIEW
This is a relatively new database that is,
off recently, being increasingly used by
iOS developers considering the benefits
it offers. There is no doubt to the fact
that Realm is faster and more efficient
than SQLite and Core Data.
4. Fast
Realm have seen many libraries try to offer a similar level of features on top of SQLite, at the
expense of speed. In contrast, Realm is faster than even raw SQLite on common operations,
while maintaining an extremely rich feature set.
6. Models
Realm data models are defined as regular Swift classes with regular properties. To create
one, simply subclass Object or an existing Realm model class. Realm model objects
mostly function like any other Swift objects. You can define your own methods on them,
conform them to protocols, and use them like you would any other object. The main
restriction is that you can only use an object on the thread which it was created.
import RealmSwift
// Dog model
class Dog: Object {
dynamic var name = ""
dynamic var owner: Person? // Properties can be optional
}
// Person model
class Person: Object {
dynamic var name = ""
dynamic var birthdate = Date(timeIntervalSince1970: 1)
let dogs = List<Dog>()
}
7. Required properties
String, Date, and Data properties can be declared as optional or required (non-optional)
using standard Swift syntax. Optional numeric types are declared using the RealmOptional
type:
class Person: Object {
// Optional string property, defaulting to nil
@objc dynamic var name: String? = nil
// Optional int property, defaulting to nil
// RealmOptional properties should always be declared with `let`,
// as assigning to them directly will not work as desired
let age = RealmOptional<Int>()
}
let realm = try! Realm()
try! realm.write() {
var person = realm.create(Person.self, value: ["Jane", 27])
// Reading from or modifying a `RealmOptional` is done via the `value` property
person.age.value = 28
}
RealmOptional supports NSData,NSDate,Int, Float, Double, Bool, and all of the sized
versions of Int (Int8, Int16, Int32, Int64).
8. Create Objects
When you have defined a model you can instantiate your Object subclass and add the new instance to
the Realm. Consider this simple model:
class Dog: Object {
@objc dynamic var name = ""
@objc dynamic var age = 0
}
// (1) Create a Dog object and then set its properties
var myDog = Dog()
myDog.name = "Rex"
myDog.age = 10
// (2) Create a Dog object from a dictionary
let myOtherDog = Dog(value: ["name" : "Pluto", "age": 3])
// (3) Create a Dog object from an array
let myThirdDog = Dog(value: ["Fido", 5])
// Get the default Realm
let realm = try! Realm()
// You only need to do this once (per thread)
// Add to the Realm inside a transaction
try! realm.write {
realm.add(myDog)
}
9. Updating Objects
Realm provides a few ways to update objects, all of which offer different tradeoffs depending on the situation.
// Query and update from any thread
DispatchQueue(label: "background").async {
autoreleasepool {
let realm = try! Realm()
let theDog = realm.objects(Dog.self).filter("age == 1").first
try! realm.write {
theDog!.age = 3
}
}
}
10. Deleting Objects
Pass the object to be deleted to the Realm().delete(_:) method within a write transaction.
// let cheeseBook = ... Book stored in Realm
// Delete an object with a transaction
try! realm.write {
realm.delete(cheeseBook)
}
// Delete all objects from the realm
try! realm.write {
realm.deleteAll()
}
11. Queries
If you’re familiar with NSPredicate, then you already know how to query in Realm. Objects, Realm, List
and Results all provide methods that allow you to query for specific Object instances by simply passing in
an NSPredicate instance, predicate string, or predicate format string just as you would when querying an
NSArray.
// Query using a predicate string
var tanDogs = realm.objects(Dog.self).filter("color = 'tan' AND name BEGINSWITH 'B'")
// Query using an NSPredicate
let predicate = NSPredicate(format: "color = %@ AND name BEGINSWITH %@", "tan", "B")
tanDogs = realm.objects(Dog.self).filter(predicate)