Search code examples
iosobjective-cdatabaserealm

How to write different objects of Realm in same time?


I'm detecting errors such as "realm already in write transaction". My application using:

    [[RLMRealm defaultRealm] beginWriteTransaction];
    [[RLMRealm defaultRealm] addOrUpdateObject:user];
    [[RLMRealm defaultRealm] commitWriteTransaction];

I am using this methods for different objects in different places of my app. So, what's the best way to prevent these errors? Is is possible to control multiple write operations asynchronous?


Solution

  • As you've discovered, Realm doesn't allow write transactions to be nested (you cannot start a new transaction before committing or cancelling the previous one).

    Avoiding this issue is mainly an architectural design problem. A write transaction shouldn't do anything except add, delete, or modify objects in a Realm. You may want to use the transactionWithBlock: method mentioned by EpicPandaForce in the comments, and/or create helper methods whose sole responsibility is to start, carry out, and finish a write transaction.

    If you really need to be able to check whether a Realm is already in a write transaction, you can use the inWriteTransaction property. But if you need to use this property, in almost all cases the way you're structuring your app is deficient and you should go back and reconsider why your write transactions are so complicated.