How to deal with thread and the kingdom? (IOS)

I use Realm to store model objects. In my object, I have a function that generates NSDataproperties from its own values. This generation can be long, so I would like to generate mine NSDatain a stream with a handler block .

My problem is that access to Realm data is only possible for the Realm creation object (actually the main thread). Therefore, when I access my properties RealmObjectin the stream, the application crashes. According to the specifications of Realm, this is normal. But what is the best solution for generating my generation NSDatain a stream depending on the Realm limit?

I actually have two ideas:

  • create a special dispatch queue in Realm and do all my access rights to Realm in this queue
  • get all the necessary properties in the temp structure (or a set of variables) and work with this structure / variables to generate mine NSDatain the stream.

I assume that many Realm users should deal with streams and Realm, so what did you do in this case?

+4
source share
1 answer

Pass the object identifier to the code running in a separate thread. Inside this thread, create an instance of Realm ( let realm = try! Realm()) and retrieve your object. Then you can make your long generation and return the result with a callback.

let objectId = "something"
dispatch_async(queue) {
  let realm = try! Realm()
  let myObject = realm.objectForPrimaryKey(MyObject.self, key: objectId)
  let result = myObject.longOperation()

  // call back with results
}

or

let objectRef = ThreadSafeReference(to: myObject)
DispatchQueue(label: "background").async {
   let realm = try! Realm()
   guard let myObject = realm.resolve(objectRef) else {
     return // object was deleted
   }

   let result = myObject.longOperation()
  // call back with results
}
+5

All Articles