gpt4 book ai didi

iOS - 更改 REALM 对象属性时应用程序崩溃

转载 作者:行者123 更新时间:2023-11-28 23:25:11 25 4
gpt4 key购买 nike

我在项目中使用 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 数据库写入了几个 Diary 对象。我也可以使用下面的代码获取它们

    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

关于iOS - 更改 REALM 对象属性时应用程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58913485/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com