如何将Realm属性更改为可为空? [英] How to change Realm property to nullable?

查看:273
本文介绍了如何将Realm属性更改为可为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How to change CalendarEvent.notes to optional (nullable)?

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.

The Realm database is already populated with data. I want the notes property to be changed to nullable in the Realm database. If I try @objc dynamic var notes: String? = "" a runtime error appears stating Migration is required due to the following errors: - Property 'CalendarEvent.notes' has been made optional.

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

According to the Realm documentation, renaming a property during a migration is a way to acheive this. Is it possible to change this property to nullable and without renaming?

推荐答案

您可以在迁移块中进行处理,并且使用相同的属性名称就可以了.这是将非可选的first_name属性迁移到可选的first_name属性的代码.

You can just handle this in the migration block and using the same property name is fine. Here's the code that would migrate a non-optional first_name property to an optional first_name property.

原始对象看起来像这样

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

然后将属性更改为可选

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

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

and here's the migration block to do that. The first version was 1 (with the non-optional first_name) and version 2 is has the updated object.

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"]
         }
     }
 })

这将保留现有数据的完整性.当我们的应用程序需求发生变化时,我们一直在使用这种迁移方式.

This will leave the existing data intact. We use this kind of migration all of the time as our app needs change.

这篇关于如何将Realm属性更改为可为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆