Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Cannot create asynchronous query while in a write transaction" exception

After migrating mine OS X application from swift 2.2 to swift 3.0 (realm version has also changed from 1.0.2 to 2.1.1) some of write transactions began to throw an exception: "Cannot create asynchronous query while in a write transaction". But it was working fine before the migration.

let realm = try Realm()
let allMessages = realm.objects(Message.self)
let messages = allMessages.filter("(state == 1) AND (dateSent <= %@)",  dateSent)
try realm.write ({
   messages.forEach { message in message.state = .seen }
})

At the beginning of the transaction it throws an exception. Why this is happening and how could I fix it?

like image 719
jufina Avatar asked Jan 12 '17 12:01

jufina


1 Answers

Was facing the same issue in my code, and it turned out that beginning the write transaction was triggering a collection notification that in turn created a new RLMResults and added a notification block to it, which means I was calling addNotificationBlock inside of a write transaction and crashing.

If you can reproduce, put a breakpoint in results.cpp - void Results::prepare_async() where the exception is thrown and see what your code is trying to do.

like image 193
LeffelMania Avatar answered Nov 15 '22 06:11

LeffelMania