0

我在一个项目中使用 RealmSwift。我有一个模型如下

 @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)
    }
}

我写了几个 Diary 对象到 REALM db。我也可以使用下面的代码来获取它们

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

获取这些对象后,我只是尝试更新对象的属性,然后应用程序崩溃了。代码如下,

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

控制台消息:libc++abi.dylib:以 NSException 类型的未捕获异常终止

任何帮助都会很棒,谢谢。

4

1 回答 1

1

您需要在写入事务中更新您的对象。您的代码应类似于:

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"
    }
}

要复制您的对象,您可以这样做:

let currentNoteCopy = Diary(value: notes[0])
currentNoteCopy.id = 2
于 2019-11-18T11:33:27.783 回答