Search code examples
iosswiftmultithreadingrealmdispatch

How to deal with thread and Realm ? (iOS)


I use Realm to store my model objects. In my object I have a function which generate NSData from its own properties values. This generation can be long, So I would like to generate my NSData in a thread with handler block.

My problem is that Realm data access is only possible on the Realm creation entity (actually the main thread). So when I access to my RealmObject properties in a thread, application crash. According to Realm specs, it's normal. But what is the best solution to make my NSData generation in a thread depending to Realm limitation ?

Actually I have two ideas :

  • make a Realm specific dispatch queue and make all my Realm access write in this queue
  • get all properties in need in a temp struct(or a set of variables) and work with this struct/variables to generate my NSData in a thread.

I assume that a lot of Realm users need to deal with threads and Realm, so what did you do in this kind of case ?


Solution

  • Pass the object id to the code that is running in the separate thread. Within that thread create a Realm instance (let realm = try! Realm()) and retrieve your object. Then you can do 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 {
    
       autoreleasepool {
            let realm = try! Realm()
            guard let myObject = realm.resolve(objectRef) else {
                return // object was deleted
            }
    
            let result = myObject.longOperation()
            // call back with results
       }
    }