警告:我是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对象中读取数据,因此该函数工作正常。我在 类AppDelegate:UIResponder,UIApplicationDelegate { 上获得了SIGABRT。没有完整的示例显示领域文档或示例中的更新。我也尝试过使用realm.create和相应的参数,但仍然没有。它看起来很简单,所以我确定我做的事情很愚蠢。任何帮助都会很棒。谢谢!
答案 0 :(得分:2)
在这里咬你的是,一旦你向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)
}