0

I am using RealmSwift in a project. I have a model as below

 @objc final class Diary : Object, Codable {
     @objc dynamic public var id: Int = 1
     @objc dynamic public var notes: String = ""
 }
public func persistDiary(){
    let realm = StorageServiceManager.shared.getRealm()
    do{
        try realm.write {
            realm.add(self)
        }
    }catch{
        debugPrint(error)
    }
}

I wrote few Diary objects to the REALM db. I was able to fetch them also using below code

    let realm = StorageServiceManager.shared.getRealm()
    let notes = realm.objects(Diary.self)

After fetching those objects, I just tried updating a property of an object and the app got crashed. The code for that is as below,

    var currentNotes = notes[0]
    currentNotes.id = 2//This line leads to the crash
    currentNotes.notes = "testing"

Console message: libc++abi.dylib: terminating with uncaught exception of type NSException

Any help will be great, Thanks.

jegadeesh
  • 875
  • 9
  • 22

1 Answers1

1

You need to update your object inside a write transaction. Your code should look something like:

let realm = try! Realm()
let notes = realm.objects(Diary.self)

if let currentNotes = notes[0] {
    try! realm.write {
       currentNotes.id = 2//This line leads to the crash
       currentNotes.notes = "testing"
    }
}

To make a copy of your object, you can do it like this:

let currentNoteCopy = Diary(value: notes[0])
currentNoteCopy.id = 2
Marina Aguilar
  • 1,151
  • 9
  • 26
  • I don't want to write the object at this time. I just want to update the object for writing it later. – jegadeesh Nov 18 '19 at 11:53
  • Ok, in that case you might wanna make a copy of your object. Check edit. – Marina Aguilar Nov 18 '19 at 11:54
  • I had to do all modifications of a realm object after calling beginWrite method of realm. Similarly to save or discard the changes I had to call relative methods. – jegadeesh Nov 18 '19 at 12:27
  • Great! Is it fixed, then? – Marina Aguilar Nov 18 '19 at 15:52
  • Yes, it is fixed. But I'm not sure I'm doing it in a correct way. Because I show a modal view controller and on viewDidLoad I call the beginWrite method and wait for user to either cancel editing or confirm their changes. After that only I call cancel or commit write of realm. Do you have any suggestions on this? – jegadeesh Nov 19 '19 at 06:15