问题
I am removing an old unused table from the schema. How can I delete it (DROP Table) from older versions of the app? What I have tried so far
- Removed
GameScore.self
fromconfigration.objectTypes
- Bumped schema version
- Run the app
- Opened Realm Studio and the table GameScore is still there with the data that was already there previously
Adding
config.migrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 10 {
migration.enumerateObjects(ofType: "GameScore", { (oldObject, newObject) in
if let oldObject = oldObject {
migration.delete(oldObject)
}
})
}
}
Will remove all the data from GameScore. I still don't get why realm doesn't remove the GameScore table completely (I can still see it with Realm Studio)
回答1:
To completely delete a table (called CLASS in realm terms) one needs to do the following:
config.migrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 10 {
migration.deleteData(forType: "GameScore")
}
}
My initial solution
config.migrationBlock = { migration, oldSchemaVersion in
if oldSchemaVersion < 10 {
migration.enumerateObjects(ofType: "GameScore", { (oldObject, newObject) in
if let oldObject = oldObject {
migration.delete(oldObject)
}
})
}
}
Will only delete the contents of that table, it clears out the data but doesn't remove the table from the db.
回答2:
Dropping a table would be the same as deleting a Realm Object from a Realm and all of it's data.
If that's the case, there's no need for iteration. In your migration block just use deleteData(forType:)
Deletes the data for the class with the given name.
All objects of the given class will be deleted. If the Object subclass no longer exists in your program, any remaining metadata for the class will be removed from the Realm file.
Three steps
1) Remove the Realm Object class from your code
2) Increment the schemaVersion in your migration block. This notifies realm there's a new schema
3) Delete the object and it's data within the migration block by using a string of it's name.
Suppose we are working on schema version 1 and have a TestClass Realm object we want to get rid of. Remove the class from your code, increment to schema 2 and use deleteData
let config = Realm.Configuration (
schemaVersion: 2,
migrationBlock: { migration, oldSchemaVersion in
migration.deleteData(forType: "TestClass")
})
来源:https://stackoverflow.com/questions/57571473/drop-a-table-in-a-realmswift-migration