在 swift 中尝试更新领域对象时获取 SIGABRT

Getting SIGABRT when trying to update a realm object in swift

警告:我是 iOS、Swift 和 Realm 的新手。我在 Realm 中保存和检索没有问题,但我似乎无法在不崩溃的情况下更新现有对象。

AppDelegate:

class Bale: Object {
    dynamic var uid = NSUUID().UUIDString
    dynamic var id = 0
    dynamic var number = 0
    dynamic var type = 0
    dynamic var weight = 0
    dynamic var size = ""
    dynamic var notes = ""
    override static func primaryKey() -> String? {
        return "uid"
    }
}

其他地方:(xcode坚持所有!)

    let bale: Bale = getBaleByIndex(baleSelected)
    bale.id = Int(textID.text!)!
    bale.number = Int(textNumber.text!)!
    bale.type = Int(textType.text!)!
    bale.weight = Int(textWeight.text!)!
    bale.size = textSize.text!
    bale.notes = textNotes.text!

    try! realm.write {
        realm.add(bale, update: true)
    }

getBaleByIndex:

func getBaleByIndex(index: Int) -> Bale {
    return bales[index]
}

我从其他地方的 getBaleByIndex 返回的 Bale 对象中读取数据,所以该函数工作正常。我在 class AppDelegate: UIResponder, UIApplicationDelegate { 上收到 SIGABRT。领域文档或示例中没有显示更新的完整示例。我也尝试过使用 realm.create 和适当的参数,但仍然不行。它看起来很简单,所以我确定我在做一些愚蠢的事情。任何帮助都会很棒。谢谢!

让你头疼的是,一旦你将一个对象添加到 Realm,数据就不仅仅存储在内存中,而是直接存储在持久存储中。您必须在写入事务中对您的对象进行所有修改,并且它们将在写入事务提交后自动生效。如果之前已保存,则无需再次将其添加到 Realm 中。因此,您需要将代码更改为:

try! realm.write {
    let bale: Bale = getBaleByIndex(baleSelected)
    bale.id = Int(textID.text!)!
    bale.number = Int(textNumber.text!)!
    bale.type = Int(textType.text!)!
    bale.weight = Int(textWeight.text!)!
    bale.size = textSize.text!
    bale.notes = textNotes.text!

    // Not needed, but depends on the implementation of `getBaleByIndex`
    // and whether there is the guarantee that it always returns already
    // persisted objects.
    //realm.add(bale, update: true)
}