1
votes

Working with realm 5.3.0 on swift 5.2. I have 2 cases: when I want to add new item to table and when I want to update. Function realm.add(_:update:) have to solve my problem, but item is creating and cannot updating. When I try to update, I got:

Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.

There are method, where I calling write function:

try! realm.write {
    realm.add(note, update: .modified)
}

And model:

class Note: Object {
    @objc dynamic var id : String = ""
    @objc dynamic var name : String = ""
    @objc dynamic var descr : String = ""
    @objc dynamic var dateTime : Date = Date()
    
    override static func primaryKey() -> String? {
      return "id"
    }
    
    init(id: String, name: String, descr: String, dateTime: Date) {
        self.id = id
        self.name = name
        self.descr = descr
        self.dateTime = dateTime
    }
    
    required init() {}
}
1
Which line of code is throwing that error? - Dávid Pásztor
You should probably fix your realm object. Remove required init() {}. Then the init method should be convenience init with the first line being self.init(). Oh - also insure you are populating your primary key with something, not just "". Like @objc dynamic var id : String = UUID().uuidString - Jay

1 Answers

1
votes

You just need to update your object inside write scope instead of using realm.add command again. Realm will automatically update the object in database

try! realm.write {
   //Modify Node here
}