Search code examples
iosswiftrealm

RealmSwift - transaction completion


How do I know when a particular transaction has completed?

I want to run a particular block of code after a transaction is complete. How can I do this?

I am performing writes in the following war -

do {

  try realm.write({
    realm.add(<some object>)
  })
}
catch {}

Solution

  • Best approach would be to write the method as an extension for Realm object.

    For Swift 3+

    extension Realm {
    
        /// Performs actions contained within the given block 
        /// inside a write transaction with completion block.
        ///
        /// - parameter block: write transaction block
        /// - parameter completion: completion executed after transaction block
        func write(transaction block: (Void) -> Void, completion: (Void) -> Void) throws {
            try write(block)
            completion()
        }
    }
    

    Swift 2.0

    extension Realm {
    
        /** Performs actions contained within the given block inside a write transaction with
        completion block.
    
         - parameter block: write transaction block
         - completion: completion executed after transaction block
        */
        func write(@noescape transactionBlock block: Void -> (), completion: Void -> ()) throws {
            do {
                try write(block)
                completion()
            } catch {
                throw error
            }
        }
    }
    

    Now you can use the extension just like a regular write(_:) method.

    let realm = try! Realm()
    let object = SomeObject()
    
    try! realm.write(
            transactionBlock: {
                realm.add(object)
            },
            completion: {
                print("Write transaction finished")
        })