Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Global Use of Realm Instance in Swift

Tags:

swift

realm

In each of my view controllers where I use Realm, I add the realm as a property to each class:

//Whatevs.swift
class Whatevs:NSViewController{
  let realm = try! Realm()
}

I then reference it throughout the class via self.realm.

Is there any reason not to make it a globally available instance like this?

//Global.swift <-- General swift file in my app
let realm = try! Realm() //<-- Not inside a class
like image 869
Clifton Labrum Avatar asked Dec 06 '25 06:12

Clifton Labrum


1 Answers

Actually, it's usually discouraged from hanging onto Realm instances at all if it can be helped. :)

Once Realm() is called on a specific thread, that instance will be internally cached by Realm and the same instance will be returned on subsequent Realm() calls. As a result, there's no tangible performance gains from hanging onto a Realm instance as a class member like that.

If you do any kind of threaded operations in your app, you need to be careful with storing Realm references since calling self.realm on a background thread will then trigger an exception.

If you're dealing with just the default Realm, then best practice is to simply call let realm = try! Realm() at the time you actually need it.

If you're dealing with different types of Realms that rely on specific Configuration instances, then it's recommended to store those as global constants. Realm Configuration objects are thread-safe so they can be passed to background threads to create Realm instances there with no problems.

like image 177
TiM Avatar answered Dec 07 '25 23:12

TiM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!