the realm is already in a write transaction

The rule of thumb for Realm is only one write transaction open on an RLMRealm at any given time. You might need to reconsider your logic if you're hitting this error. You shouldn't ever intentionally be trying to open up a second write transaction on a RLMRealm that's already open on the same thread. Doing it on separate threads is fine, but the thread the second write transaction is on will be blocked until the first one completes.

If there's something in your implementation that isn't set right, it's also possible that a transaction you've assumed had completed might have had an error and was left open. Like Sebastian said, you can check this with -[RLMRealm inWriteTransaction], but in this case, you should definitely backtrack your code to see why that is happening.


Here is one possible solution that I came across in this github discussion:

extension Realm {
    public func safeWrite(_ block: (() throws -> Void)) throws {
        if isInWriteTransaction {
            try block()
        } else {
            try write(block)
        }
    }
}

use it like this:

try! realm.safeWrite{
    //your write code goes here
}

now safeWrite will check if there is active transaction and will either start one or just execute the code passed in.


If you are doing some write tasks in the same thread, you can add them to NSMutableArray, a then use addOrUpdateObjectsFromArray. On the other side, you can check to avoid write conflicts by firing inWriteTransaction on realm object.