REALM 原因:'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'

REALM reason: 'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'

我在尝试修改领域对象时遇到错误。

很简单class实际上只有一条记录

class User: Object{

    @objc dynamic var id = UUID().uuidString
    @objc dynamic var name:String  = ""
    @objc dynamic var email:String = ""
    .....

    static func getInfo() -> User? {
        do {
            let realm = try Realm()
            return realm.objects(User.self).first
        } catch {
            return nil
        }
    }

}

我调用数据:

var user = User.getInfo()

现在,当我尝试修改它时,出现以下错误。

user.name = "test"

*** 由于未捕获的异常 'RLMException' 而终止应用程序,原因:'Attempting to modify object outside of a write transaction - call beginWriteTransaction on an RLMRealm instance first.'

我做错了什么?谢谢

谢谢。

user 是一个 Realm 实例。对 user 的任何修改都需要在 realm.write 块内。

try! realm.write {
    user.name = "test"
}