【问题标题】:How to change Realm property to nullable?如何将 Realm 属性更改为可为空?
【发布时间】:2020-01-23 05:19:41
【问题描述】:

如何将CalendarEvent.notes 更改为可选(可为空)?

class CalendarEvent: Object {
    @objc dynamic var date: String = ""
    @objc dynamic var notes: String = ""
    @objc dynamic var notification: String = ""
}

Realm 数据库已经填充了数据。 我希望在 Realm 数据库中将 notes 属性更改为可为空。 如果我尝试@objc dynamic var notes: String? = "",则会出现运行时错误,说明Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.

根据 Realm 文档,在迁移期间重命名属性是实现此目的的一种方法。是否可以将此属性更改为可为空且无需重命名?

【问题讨论】:

  • 试试这个@objc dynamic var date: String?
  • @Anbu.Karthik 这会导致运行时错误指出Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.
  • 您必须更新架构版本,例如`let configuration = Realm.Configuration(schemaVersion: 2)`
  • 我正在尝试执行此stackoverflow.com/a/48899642/10555547 但在 Realm swift 中代替

标签: ios swift realm


【解决方案1】:

您可以在迁移块中处理此问题,并使用相同的属性名称。下面是将非可选的 first_name 属性迁移到可选的 first_name 属性的代码。

原来的对象是这样的

class PersonClass: Object {
    @objc dynamic var first_name = ""

然后我们将属性改为可选

class PersonClass: Object {
    @objc dynamic var first_name: String? = nil

这是执行此操作的迁移块。第一个版本是 1(带有非可选的 first_name),而版本 2 是更新后的对象。

let vers = UInt64(2)
let config = Realm.Configuration( schemaVersion: vers, migrationBlock: { migration, oldSchemaVersion in
     print("oldSchemaVersion: \(oldSchemaVersion)")
     if (oldSchemaVersion < vers) {
        print("  performing migration")

        migration.enumerateObjects(ofType: PersonClass.className()) { oldItem, newItem in
            newItem!["first_name"] = oldItem!["first_name"]
         }
     }
 })

这将使现有数据保持不变。随着应用需求的变化,我们一直使用这种迁移方式。

【讨论】:

  • 谢谢杰,这正是我想要的
猜你喜欢
  • 1970-01-01
  • 2017-02-05
  • 2021-11-19
  • 1970-01-01
  • 2011-04-22
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
相关资源
最近更新 更多