utkbansal utkbansal - 1 year ago 147
Swift Question

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 {}

Answer Source

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

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)
        } 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: {
        completion: {
            print("Write transaction finished")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download