本文介绍了Swift中的领域迁移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个建模的领域对象
I have a Realm Object modeled as so
class WorkoutSet: Object {
// Schema 0
dynamic var exerciseName: String = ""
dynamic var reps: Int = 0
// Schema 0 + 1
dynamic var setCount: Int = 0
}
我正在尝试执行迁移.
在我的AppDelegate
中,我已经导入了RealmSwift
.
Within my AppDelegate
I have imported RealmSwift
.
在函数didFinishLaunchWithOptions
中,我调用
Migrations().checkSchema()
迁移是在另一个文件中声明的类.
Migrations is a class declared in another file.
在该文件中,有一个声明为这样的结构.
Within that file there is a struct declared as so.
func checkSchema() {
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: 1,
// 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
// We haven’t migrated anything yet, so oldSchemaVersion == 0
switch oldSchemaVersion {
case 1:
break
default:
// Nothing to do!
// Realm will automatically detect new properties and removed properties
// And will update the schema on disk automatically
self.zeroToOne(migration)
}
})
}
func zeroToOne(migration: Migration) {
migration.enumerate(WorkoutSet.className()) {
oldObject, newObject in
let setCount = 1
newObject!["setCount"] = setCount
}
}
将setCount
添加到模型时出现错误
I am getting an error for adding setCount
to the model
推荐答案
您将需要调用迁移.仅创建配置,将不会调用它.有两种方法可以做到这一点:
You will need to invoke the migration. Merely creating a configuration, won't invoke it. There are two ways of doing this:
-
通过迁移将您的配置设置为Realm的默认配置-
Set your configuration with migration as Realm's default configuration-
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: 1,
// 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 < 1 {
migration.enumerate(WorkoutSet.className()) { oldObject, newObject in
newObject?["setCount"] = setCount
}
}
}
)
Realm.Configuration.defaultConfiguration = config
OR
- 使用migrateRealm手动迁移:
现在,您的迁移应该可以正常工作了.
Now your migration should work properly.
这篇关于Swift中的领域迁移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!