问题
I am using RealmSwift
for my project. However, I'm not sure how to tackle the following:
RMLException
: Attempting to modify object outside of a write transaction - callbeginWriteTransaction
on anRLMRealm
instance first
thrown.
Anyone any clue?
import RealmSwift
func createOrUpdateMachineInRealm(machine: Machine){
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
let realm = Realm()
realm.beginWrite()
realm.write{
realm.add(machine, update: true)
}
realm.commitWrite()
dispatch_async(dispatch_get_main_queue()) {
// update some UI
actionDelegate?.operationCompleted(true)
}
}
}
Solution: I pass in the parameters for machine as well and assign them to the machine within the realm.write()
func createOrUpdateMachineInRealm(machine: Machine, name: String){
let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
dispatch_async(dispatch_get_global_queue(priority, 0)) {
// do some task
let realm = Realm()
realm.write{
machine.name = name
realm.add(machine, update: true)
}
}
}
回答1:
I just had the same problem and exception as you did. Though Nate Mann's answer is not the solution to the problem, it lead me in the right direction.
You can not modify a Realm object you have previously pulled out of the database, because Realm will try to update it and throw an error, when it is (for whatever reason) on a different queue.
So you either have to do all modification inside your realm.write{ }
statement or create a new object with the same primary key, so it gets updated correctly. That would also mean that you can't have one function to create or update, but need two separate ones.
Your update function would have to look something like this:
func updateMachineInRealm(machine: Machine){
var updatedMachine = Machine()
updatedMachine.name = machine.name
updatedMachine.value = machine.value + 42
updatedMachine.primaryKey = machine.primaryKey
// "transfer" or modify all the values of the old machine object
let realm = try! Realm()
do {
try realm.write() {
realm.add(updatedMachine, update: true)
}
}
Remember that you need a unique primary key for this code to work, because that is what Realm will match your new object with in the database.
Also, this of course has drawbacks when working on a bigger project with more than one thread accessing Realm objects etc. But it'll work for small projects (like I was working on and you seem to be working on).
回答2:
Get rid of realm.beginWrite()
and realm.commitWrite()
. They are not needed when you use realm.write { }
.
来源:https://stackoverflow.com/questions/30756349/realmswift-rlmexception