Swift Realm:在编写事务引用后将其设置为nil [英] Swift Realm: After writing transaction reference set to nil

查看:97
本文介绍了Swift Realm:在编写事务引用后将其设置为nil的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

class Family: Object {
    dynamic var name = ""
    var members = List<FamilyMember>()
}

class FamilyMember: Object {
    dynamic var name = ""
    dynamic var belongsToFamily: Family?
}

let realm = try! Realm()

let familyMember = FamilyMember()
familyMember.name = "NameExample"

let newFamily = Family()
newFamily.name = "Familyname"

try! realm.write {
    newFamily.members.append(familyMember)
    familyMember.belongsToFamily = newFamily
    realm.add(newFamily)
    realm.add(familyMember)
}

问题:为什么Realm进行写交易后,familyMember.belongsToFamily设置为nil?

QUESTION: Why is familyMember.belongsToFamily set to nil after Realm's writing transaction?

推荐答案

这是预期的行为.在实际访问属性之前,Realm不会复制任何数据.访问属性时,Realm直接从其文件中获取数据.因此,Realm不会将任何数据存储到其ivar.此外,Realm对象在持久化时将更改为另一个类.这就是为什么您无法通过调试器看到任何值,并且在提交后将所有值都取消掉的原因.

It's intended behavior. Realm does not copy any data until actually access the properties. When access the properties, Realm fetch the data directly from its file. So Realm does not store any data to its ivar. Additionally, Realm object will change to another class at the moment it is persisted. That's why you cannot see any values via the debugger and nil out all value after committed.

因此,如果要调试对象值,可以在调试控制台中使用po命令,也可以仅使用print()方法.

So if you'd like to debug objects value, you can use po command in debug console, or just use print() method.

另请参见 https://realm.io/docs/swift/latest/#debugging

使用Realm的Swift API调试应用程序必须通过LLDB控制台完成.

Debugging apps using Realm’s Swift API must be done through the LLDB console.

请注意,尽管通过我们的Xcode插件安装的LLDB脚本允许在Xcode的用户界面中检查Realm变量的内容,但这不适用于Swift.而是,这些变量将显示不正确的数据.相反,您应该使用LLDB的po命令来检查存储在Realm中的数据内容.

Note that although the LLDB script installed via our Xcode Plugin allows inspecting the contents of your Realm variables in Xcode’s UI, this doesn’t yet work for Swift. Instead, those variables will show incorrect data. You should instead use LLDB’s po command to inspect the contents of data stored in a Realm.

另请参见: https://github.com/realm/realm-cocoa/issues/2777

这篇关于Swift Realm:在编写事务引用后将其设置为nil的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆