Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Realm primary key migration

Tags:

ios

swift

realm

I want to migrate my realm schema to a new version. Therefor the removal of my primary key is needed.

Old schema:

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

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

New schema:

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

Without migration, realm will fail with

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

I tried this migration block, which failed too:

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

'RLMException', reason: 'Invalid property name'

Is there a way to remove the primary key when migrating realm to a new schema version?

like image 280
vonox7 Avatar asked Jul 02 '15 10:07

vonox7


1 Answers

You do not need to do anything in migration block if you only remove the primary key annotation. But there is a need to increase the schema version because schema definitions changed.

Like below:

// 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()
...
like image 51
kishikawa katsumi Avatar answered Oct 05 '22 02:10

kishikawa katsumi