Search code examples
iosswiftmultithreadingrealm

Accessing realm and filter results in different threads


Hello everyone!

I've run into a big problem. I'm trying to access the realm data in main thread but also since I need to do a lot of synchronizing operations with the data such as update, insert etc I decided to search if there is a possibility to do all of these operations asynchronously but I'm getting different errors for every method that I'm trying to implement.

I'm creating the realm database as follows:

realm = try Realm(configuration: Realm.Configuration(
                  fileURL: fileURL,
                  encryptionKey: nil,
                  schemaVersion: schemaVersion,
                  objectTypes: objectTypes))

Accessing data as follows:

guard let realm = realm else {
  return nil
}
let results = realm.objects(SPUserModel.self)
return Array(results)

Doing all of these upsert operations in the mainthread will raise my memory up to 1GB which is bad. Making them asynchronously may be a solution but there are different threads and that's an issue.

Would be glad if you can help me with this.


Solution

  • extension Realm {
    class func realmInstance() -> Realm? {
       let realm = try Realm(configuration: Realm.Configuration(
                      fileURL: fileURL,
                      encryptionKey: nil,
                      schemaVersion: schemaVersion,
                      objectTypes: objectTypes))
       return realm
    }
    

    access :

    DispatchQueue(label: "background").async {
        Realm.realmInstance()?.objects(SPUserModel.self)
    }