Search code examples
swiftmacosrealmrealm-mobile-platform

Realm Server Object Incorrect Thread Exception


I had an app were realm objects were managed locally like this

import Foundation
import RealmSwift

class Patient: Object {

    static var realm: Realm?
    dynamic var name = ""

    convenience init(name: String, save: Bool = false) {
        self.init()
        self.name = name
        if save() {
            self.save
        }
    }


    func save() {
        try! Patient.realm?.write {
            Patient.realm?.add(self, update: true)
        }
    }

    static func getAllPatients() -> Results<Patient>? {
        return Patient.realm?.objects(Patient.self)
    }

}

When I tried to convert the above code to sync with Realm Object Server, I got thread error trying to pass the realm instance passed from the login method to my class

static func userLogin(onCompletion: @escaping (Realm) -> Void) {
    let serverURL = URL(string: "http://127.0.0.1:9080")!
    let credentials = SyncCredentials.usernamePassword(username: "test@test", password: "test")
    SyncUser.logIn(with: credentials, server: serverURL) {
        user, error in

        if let user = user {
            let syncServerURL = URL(string: "realm://localhost:9080/~/test")!
            let config = Realm.Configuration(syncConfiguration: SyncConfiguration(user: user, realmURL: syncServerURL))
            let realm = try! Realm(configuration: config)
            onCompletion(realm)
        } else if _ = error {
        }
    }

} 

and here to get the realm instance

userLogin() { realm in
        Patient.realm = realm
    }

Now, when I use this new Patient.realm in my class functions (getAllPatients), I get incorrect thread exception

Any possible way to pass the realm instance from userLogin to my class without causing this thread exception? If I put my queries in the login function, does that mean I need to login, sync everytime I need to get something from or edit the database?


Solution

  • In your login function you should be storing the Realm.Configuration object created with the logged-in user and using that to create a Realm instance as needed rather than trying to store the Realm object. Realm instances are thread-specific, while config objects are not.