【问题标题】:Unable to do a Realm migration in Swift无法在 Swift 中进行领域迁移
【发布时间】:2018-08-02 19:41:35
【问题描述】:

我有一个提醒对象,我刚刚修改了它。这是原始版本:

class Reminder: Object {
   @objc dynamic var title = ""
   @objc dynamic var parents = ""
   @objc dynamic var lists = "All"
   @objc dynamic var labels = "All"
   @objc dynamic var priority = 
   @objc dynamic var notes = ""
   @objc dynamic var reminderType = .none
}

这是新版本:

class Reminder: Object {
    @objc dynamic var title = ""
    @objc dynamic var parents = ""
    @objc dynamic var lists = "All"
    @objc dynamic var dueDate = 0.0
    @objc dynamic var reminderDate = 0.0
    @objc dynamic var reminderLocation = ""
    @objc dynamic var labels = "All"
    @objc dynamic var priority = 1
    @objc dynamic var notes = ""
}

我已经实现了 AppDelegate 的迁移块didFinishLaunchingWithOptions 方法。这里是:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    ///Realm migration
    let config = Realm.Configuration(
        // Set the new schema version. This must be greater than the previously used
        // version (if you've never set a schema version before, the version is 0).
        schemaVersion: 2,

        // Set the block which will be called automatically when opening a Realm with
        // a schema version lower than the one set above
        migrationBlock: { migration, oldSchemaVersion in

            if oldSchemaVersion < 2 {

            }
    }
    )
    Realm.Configuration.defaultConfiguration = config
    let _ = try! Realm()

    return true
}

根据文档,我认为应该是功能迁移。但是,在编译应用程序时出现以下错误:

Fatal error: 'try!' expression unexpectedly raised an error: Error Domain=io.realm Code=10 "Migration is required due to the following errors:
- Property 'Reminder.reminderLocation' has been added.
- Property 'Reminder.reminderDate' has been added.
- Property 'Reminder.dueDate' has been added.
- Property 'Reminder.reminderType' has been removed."

我应该在迁移块中进行哪些更改?

提前谢谢你

【问题讨论】:

    标签: swift realm realm-migration


    【解决方案1】:

    当存储的数据与代码中的模型不匹配时,将引发此异常。

    您不需要在迁移块中执行任何操作,但是您需要通过更新 Realm.Configuration.schemaVersion 的值来触发迁移,例如:

    schemaVersion: 3,
    

    【讨论】:

    • 我已经将schemaVersion的值更新为2(之前是1),但它不起作用。我只是再次尝试并将其设置为 3 无济于事。关于可能导致它的任何其他想法?
    • 奇怪,你可能需要编写迁移块来添加默认值。这也可能与原始版本中的枚举有关,因为 Realm 并不专门支持枚举。你已经发布了应用程序吗?开发过程中的快速解决方法是删除现有应用并重新安装。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2019-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多