sheinix
sheinix

Reputation: 187

Swift Realm Saving prefetched objects into new Object

I'm having some problems working with Realm. Basically I'm fetching objects from an API in background using Alamofire, mapping them to an Object with ObjectMapper, saving with Realm in background, and going back to the main thread to show them. I know Realm Objects are thread confined if they are managed, but still I'm confused about how to use them after they were saved:

1) Fetch data, map it, and save it:

network.makeCallWith(urlRequest: objCreation, objectType: objType.self) { (response) in......

//.....
DispatchQueue.global(qos: .background).async {

        do {

            let realm = try Realm()

            try realm.write {

                for obj in objects { //obj in response

                    realm.add(obj,update: true)
                }

            }
        } catch let error as NSError {

            print(error)
        }

        DispatchQueue.main.async {

            do {

                let realm = try Realm()

                let objects = realm.objects(T)

                completion(Result.success(Array(objects)))

            } catch let error as NSError {

                print(error)
            }

        }
    }

At this point I can use the object in the main thread. The problem is when I have to save another object that I fetched after this one, and NEEDS the previously saved object as a property (relationship). I'm getting the "Can not add objects from a different Realm" error.

Is this a good approach for using a previously saved object as a property of another one?

Upvotes: 1

Views: 757

Answers (1)

jpsim
jpsim

Reputation: 14409

Please use ThreadSafeReference wrappers in order to pass Realm objects between threads: https://realm.io/docs/swift/latest/#passing-instances-across-threads

Upvotes: 1

Related Questions