如何将新属性添加到R​​ealm对象?

Shi*_*k.p 5 realm ios swift swift3

我正在尝试向Realm对象UserDetails添加一个新属性.这是我的尝试:

class CustomerDetails: Object {
   dynamic var customer_id = 0
   dynamic var customer_name = ""
}
Run Code Online (Sandbox Code Playgroud)

现在我需要将一个新属性"company_name"添加到之前已经创建的UserDetails对象中.如何向现有的Realm对象添加新的?

Shi*_*k.p 8

两种方法:

  1. 只需从模拟器中删除您的应用并再次运行即可.每次更改Realm对象的属性时,现有数据库都会与新数据库不兼容.只要您还处于开发阶段,您只需从模拟器/设备中删除该应用程序并再次启动即可.

  2. 在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()

我建议你按照第二个.


dr_*_*rto 5

您只需将属性添加到R​​ealm模型中,但必须提供迁移才能将存储的数据更新为新格式。

这包括在中设置schemaVersionRealm.Configuration以告知Realm模式已更改;在中提供,并migrationBlock为现有对象初始化新属性(可能只是通过设置一个空字符串)。在应用程序的下一次启动时,Realm将自动运行迁移,从而将存储的数据更新为新的架构。