ios – Realm主键迁移

前端之家收集整理的这篇文章主要介绍了ios – 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 = ""
}

没有迁移,领域将失败

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

我尝试了这个迁移块,它也失败了:

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

‘RLMException’,reason: ‘Invalid property name’

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

解决方法

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

如下所示:

// 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()
...
原文链接:https://www.f2er.com/iOS/333449.html

猜你在找的iOS相关文章