境界中的可选双人

时间:2018-02-12 11:03:57

标签: android kotlin realm

我已将Double属性从非可空属性更改为可空属性。

var gasPressure: Double? = null

启动应用程序时,我得到了预期的RealmMigrationNeededException并出现以下错误:

  

Property' Measurement.gasPressure'已被选为。

问题是我找不到任何关于在Realm中使属性可选的信息。我发现有多个人试图在Swift中这样做但在Java或Kotlin中没有这个。

在文档中我发现了以下内容,但这只告诉我如何表明属性是必需的。

  

@Required注释可用于告诉Realm禁止字段中的空值,使其成为必需而非可选。只能使用@Required注释Boolean,Byte,Short,Integer,Long,Float,Double,String,byte []和Date。如果将其添加到其他字段类型,则编译将失败。

     

隐式需要具有基本类型和RealmList类型的字段。具有RealmObject类型的字段始终可以为空。

是否有可能在Realm中拥有可为空的Double属性,还是应该使用变通方法?

2 个答案:

答案 0 :(得分:2)

  

问题是我无法找到任何关于在Realm中使属性可选的内容。

这太可惜了,因为你实际上可以在迁移中这样做。

public class MyMigration implements Realm.Migration {
    @Override
    public void migrate(DynamicRealm realm, long oldVersion, long newVersion) {
        RealmSchema schema = realm.getSchema();
        if(oldVersion == someNumber) {
            RealmObjectSchema gasPipe = schema.get("GasPipe");
            if(gasPipe.isRequired("gasPressure")) {
               gasPipe.setRequired(false); // same as setNullable(true)
            }
            oldVersion++;
        }
    }

    // equals, hashcode
}

您需要在配置

上碰撞schemaVersion
RealmConfiguration config = new RealmConfiguration.Builder()
                                  .migration(new MyMigration())
                                  .schemaVersion(someNumber+1)
                                  .build();

答案 1 :(得分:-1)