我想将我的 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/