RLMException',原因:'尝试修改写事务之外的对象

时间:2018-05-01 08:34:42

标签: swift realm

当我遵守以下代码时,我遇到了以下错误:

  

***由于未捕获的异常'RLMException'而终止应用程序,原因:'尝试修改写事务之外的对象 - 调用   首先在RLMRealm实例上使用beginWriteTransaction。'

for outlet in brand.outlets! {
    let outl = OutletListRealm()
    outl.outletId = outlet.id
    outl.outletName = outlet.name!
    outl.brand = brand.id
    try! self.realm.write {
        self.realm.add(outl)
    }

    for override in outlet.override! {
        let overRide = OverRideObjectRealm()
        overRide.id = override.id
        overRide.name = override.name!
        overRide.brand = brand.name!
        overRide.outlet = outlet.name!
        outl.brand = brand.id
        try! self.realm.write {
            self.realm.add(overRide)
        }
    }
}

1 个答案:

答案 0 :(得分:3)

您需要在realm.write中做所有事情 只需更新您的代码,如下所示。

请参阅:https://realm.io/docs/swift/latest/#writes

for outlet in brand.outlets! {
        let outl = OutletListRealm()
        try! self.realm.write {
            outl.outletId = outlet.id
            outl.outletName = outlet.name!
            outl.brand = brand.id
            self.realm.add(outl)
        }

        for override in outlet.override! {
            let overRide = OverRideObjectRealm()
            try! self.realm.write {
                overRide.id = override.id
                overRide.name = override.name!
                overRide.brand = brand.name!
                overRide.outlet = outlet.name!
                self.realm.add(overRide)
            }
        }
    }