ios - Realm 主键迁移

标签 ios swift realm

我想将我的 Realm 架构迁移到新版本。因此需要删除我的主键。

旧模式:

class StudyState : Object
{
  dynamic var name = ""
  dynamic var x = ""
  dynamic var y = ""

  override static func primaryKey() -> String? {
    return "name"
  }
}

新模式:

class StudyState : Object
{
  dynamic var name = ""
  dynamic var x = ""
  dynamic var y = ""
}

没有迁移,realm 会失败

'RLMException', reason: 'Migration is required for object type 'StudyState' due to the following errors: - Property 'name' is no longer a primary key.'

我试过这个迁移 block ,但也失败了:

migration.enumerate(StudyState.className()) { oldObject, newObject in
  newObject?["deleted"] = false
  newObject?["primaryKeyProperty"] = ""
 }

'RLMException', reason: 'Invalid property name'

在将 Realm 迁移到新架构版本时,有没有办法删除主键?

最佳答案

如果只删除主键注释,则无需在迁移 block 中执行任何操作。 但是由于模式定义发生了变化,需要增加模式版本。

如下所示:

// You have to migrate Realm BEFORE open Realm if you changed schema definitions 
setSchemaVersion(1, Realm.defaultPath) { (migration, oldSchemaVersion) -> Void in
    if oldSchemaVersion < 1 {
        // Nothing to do!
        // Realm will automatically detect new properties and removed properties
        // And will update the schema on disk automatically
    }
}

let realm = Realm()
...

关于ios - Realm 主键迁移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31182300/

相关文章:

ios - 如何使用@available 定位低于特定操作系统的 iOS 设备

ios - 在 subview 中居中标签

java - 迁移时如何删除Realm?

android - Realm 警告 : Unclosed files for the types?

ios - 禁用编辑文本字段

ios - 高效分析 UIImage 中的主色

iphone - 多线程在获取照片时使用 GCD

html - 使用 Fuzi 使用 swift 从特定标签中抓取文本

ios - 为什么 Realm Set 对象会随机工作?

iphone - 使用 EKEvent 后清理内存