[英]iOS (Swift), Realm migration add a new property to store another realm object
[英]How to add new property to a Realm Object?
我正在尝试向Realm对象UserDetails添加一个新属性。 这是我的尝试:
class CustomerDetails: Object {
dynamic var customer_id = 0
dynamic var customer_name = ""
}
现在我需要将一个新属性“company_name”添加到之前已经创建的UserDetails对象中。 如何向现有的Realm对象添加新的?
两种方法:
只需从模拟器中删除您的应用并再次运行即可。 每次更改Realm对象的属性时,现有数据库都会与新数据库不兼容。 只要您还处于开发阶段,您只需从模拟器/设备中删除该应用程序并再次启动即可。
在AppDelegate的disFinishLaunchWithOptions方法中编写此代码:
let config = Realm.Configuration( schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in if (oldSchemaVersion < 1) { // Nothing to do! // Realm will automatically detect new properties and removed properties // And will update the schema on disk automatically } }) Realm.Configuration.defaultConfiguration = config let realm = try! Realm()
我建议你按照第二个。
您只需将该属性添加到Realm模型,但必须提供迁移才能将存储的数据更新为新格式。
这包括设置schemaVersion
在Realm.Configuration
告诉境界,模式被改变,并提供migrationBlock
其初始化现有对象的新属性(可能只是通过设置一个空字符串)。 在下一次启动应用程序时,Realm将自动运行迁移,从而将存储的数据更新为新架构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.