我有这堂课:
class IndiClass: Object {
dynamic var MediIndiGrpId = 0
dynamic var MediIndiGrpName = ""
let Medis = List<MediClass>()
override static func primaryKey() -> String? {
return "MediIndiGrpId"
}
}
我想现在将MediClass对象添加到列表中。 此代码显示了我如何获取对象以及如何尝试添加MediClass对象:
//Get a MediClass Object
let medi = realm.objectForPrimaryKey(MediClass.self, key: 1)
// Get the IndiClass Object
let indi = realm.objectForPrimaryKey(IndiClass.self, key: 1)
// Try to add the MediClass Object to the IndiClass Object:
indi!.Medis.append(medi!)
最后一行停止了应用,在控制台中它显示了我:
由于未捕获的异常“RLMException”而终止应用程序,原因是:“无法在写入事务之外改变持久化数组。”
答案 0 :(得分:5)
正如错误消息所提到的,持久化对象的变异必须在写入事务中发生:
// Get a MediClass Object
let medi = realm.objectForPrimaryKey(MediClass.self, key: 1)
// Get the IndiClass Object
let indi = realm.objectForPrimaryKey(IndiClass.self, key: 1)
try! realm.write {
// Try to add the MediClass Object to the IndiClass Object:
indi!.Medis.append(medi!)
}