Search code examples
iosswiftrealm-ios

iOS - App crash on changing a REALM object property


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.


Solution

  • 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