Миграции области в Swift
У меня есть объект Realm, смоделированный так
class WorkoutSet: Object {
// Schema 0
dynamic var exerciseName: String = ""
dynamic var reps: Int = 0
// Schema 0 + 1
dynamic var setCount: Int = 0
}
Я пытаюсь выполнить миграцию.
Внутри моего AppDelegate я импортировал RealmSwift.
Внутри функции didFinishLaunchWithOptions я вызываю
Migrations().checkSchema()
Migrations - это класс, объявленный в другом файле.
В этом файле есть структура, объявленная как 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 к модели
2 ответа:
Вам нужно будет вызвать миграцию. Просто создав конфигурацию, вы не вызовете ее. Есть два способа сделать это:
Задайте конфигурацию с миграцией как конфигурацию по умолчанию области -
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Или
- перенос вручную с помощью migrateRealm:
MigrateRealm (config)
Теперь ваша миграция должна работать должным образом.
Потому что вы просто создаете
Realm.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 // 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) } }) let realm = try! Realm(configuration: config) // Invoke migration block if needed