Sometimes you’d like to create multiple Realms in one app. You might need a Realm to hold “drafts” of documents. The documentation doesn’t really explain this very well and is a bit hard to find. I’m currently using the version 2.4.3.

Just to go over the basics. This is how to create a default Realm. Most app’s don’t really need to use mulitple Realms

1
let realm = try! Realm()

Creating another Realm that’s not the default one is a bit trickier

1
2
3
4
5
6
let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: false)
let url = documentDirectory.appendingPathComponent("drafts.realm")
var config = Realm.Configuration()
config.fileURL = url
let draftsRealm = try! Realm(configuration: config)

Caveats

You can’t share objects between two realms.

If you have an object like so you cannot share them between two realms. They need to be seperate instances of eachother.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Document: Object {
dynamic var _id: String = ""
dynamic var textBody: String = ""
override open static func primaryKey() -> String? {
return "_id"
}
}
let defaultRealm = try! Realm()
let draftsRealm = //... refer to the way above
let fetched = defaultRealm.object(ofType: Document.self, forPrimaryKey: "someId")!
try! draftsRealm.write {
draftsRealm.add(fetched, update: true)
}

This is a nono!

Solution: Use the value intializer

1
2
3
4
5
6
7
8
let defaultRealm = try! Realm()
let draftsRealm = //... refer to the way above
let fetched: Document = defaultRealm.object(ofType: Document.self, forPrimaryKey: "someId")!
let toBePutInDraftsRealm: Document = Document(value: fetched) // this is
try! draftsRealm.write {
draftsRealm.add(fetched, update: true)
}

Document(value: fetched) creates a copy of the Document instance. It’s a copy and is not attached to defaultRealm context. It’s floating an in memory. You can then write it to a different realm.

Bonus: Helpful Realm References

You might have to refer to these different realms very frequently. Sometimes it’s good to just create a reference with an extensionMethod

1
2
3
4
5
6
7
8
9
10
11
12
extension Realm {
static var draftsRealm : Realm {
let documentDirectory = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: false)
let url = documentDirectory.appendingPathComponent("drafts.realm")
var config = Realm.Configuration()
config.fileURL = url
let realm = try! Realm(configuration: config)
return realm
}
}

Now you can just call

1
let draftsRealm = Realm.draftsRealm