gpt4 book ai didi

android - Realm 模型真的需要 getter 和 setter 吗?

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:10:49 25 4
gpt4 key购买 nike

如果 Realm 模型中的字段实际上需要 getter 和 setter,我无法在任何地方找到它的明确记录。例如,https://realm.io/docs/java/latest/api/io/realm/RealmObject.html 处的文档说

The only restriction a RealmObject has is that fields are not allowed to be final, transient' or volatile. Any method as well as public fields are allowed. When providing custom constructors, a public constructor with no arguments must be declared and be empty.

Fields annotated with Ignore don't have these restrictions and don't require either a getter or setter.

这似乎暗示它对于非忽略字段的 getter 和 setter 是必需的。然而,https://realm.io/docs/java/latest/#customizing-objects 处的文档说

It is possible to use RealmObjects almost like POJOs. Extending from RealmObject, you can let the fields be public, and use simple assignments instead of setters and getter.

然后显示没有任何 getter 和 setter 的 Realm 模型的代码,而是有我们应该使用的公共(public)字段。真的吗?我以为 Realm 甚至没有在实际字段中存储任何值,所以从中读取和写入可能是个坏主意?我的意思是他们的调试文档 https://realm.io/docs/java/latest/#debugging状态:

Unfortunately these values are wrong because the field values are not used. Realm creates a proxy object behind the scenes and overrides the getters and setters in order to access the persisted data in the Realm

所以有人可以赐教吗?我可以跳过 getter 和 setter 并只使用公共(public)字段吗?是否有任何关于此的详尽文档?

最佳答案

public 字段在大多数情况下都有效,并且从 Realm 2.0.0 开始,它们甚至可以在 RealmObjects 的构造函数中工作(允许“默认值”),并且如果您直接访问该属性,它们也可以工作。

例如,

SomeObject obj = results.get(i);
obj.blah = "Blahblah";

这是可行的,因为托管 RealmObjects 的字段访问由 Realm-Transformer 转换为代理 getter/setter 调用(在本例中,转换为 realmSet$blah 方法)。

从 0.88.0 开始就是这种情况,当时 Realm 开始作为 Gradle 插件提供。

但是,一个主要的限制proxy field access doesn't run in instrumentation tests, because the androidTestCompile scope does not run the transformer .

关于android - Realm 模型真的需要 getter 和 setter 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39602525/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com