"realm thread safe object with singleton" Code Answer

3

your first option is definitely incorrect, since threadsafereference is a single use reference as explained below. your second option might work, but it is easier to create a new reference to your realm instance any time you are trying to access it, see the explanation below.

you shouldn't store a reference to a singleton realm instance, since you cannot ensure that you will always access it from the same thread. as the realm documentation states,

instances of realm, results, or list, or managed instances of object are thread-confined, meaning that they can only be used on the thread on which they were created, otherwise an exception is thrown.

meaning that you should never try to use let realm = try! realm() to create a singleton realm instance and then try to access that everywhere from your app.

you could try using threadsafereference to create references to realm objects that can be safely shared between threads, but as the passing instances across threads part of the documentation states, these references can only be used once, so they can't be reused as a singleton.

however, there is no need for such thing, since every time you call let realm = try! realm(), the framework automatically creates a reference to your currently used realm on the thread you are on enabling you to safely interact with it as long as you don't leave that thread.

the best way to use realm in a thread-safe way is to create a new reference to your realm using let realm = try! realm() every time you move between threads and need to access your realm. this way you can ensure that you will never get the incorrect thread exception.

By CFP on June 29 2022

Answers related to “realm thread safe object with singleton”

Only authorized users can answer the Search term. Please sign in first, or register a free account.