我在一个项目中使用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)
}
}
我为REALM数据库写了一些日记对象。我也可以使用以下代码获取它们
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 类型的未捕获异常
任何帮助都会很好,谢谢。
您需要在写入事务中更新对象。你的代码应该看起来像:
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