问题
I'm using Realm for caching over the not-so-long term, and have no need to keep up with schema versions or migrating any time there's a change to a data model.
So, instead of crashing anytime there's a change to the data model, how can my app smartly handle the discrepancy by blowing away the default Realm and starting from scratch?
Thanks in advance!
回答1:
This has been working like a charm for me since Swift 2 introduced try/catch. I just call testRealmFile()
from my app delegate at launch, and all is cool after that.
func testRealmFile(){
do {
try Realm().objects(Model1)
try Realm().objects(Model2)
} catch {
print("can't access realm, migration needed")
deleteRealmFile()
}
}
func deleteRealmFile(){
if let path = Realm.Configuration.defaultConfiguration.path {
do{
try NSFileManager.defaultManager().removeItemAtPath(path)
print("realm file deleted")
} catch {
print("no realm file to delete")
}
}
}
回答2:
The Realm Configuration object now has a property called deleteRealmIfMigrationNeeded
(also available in Objective C) which if set to true
will automatically delete the Realm database file if migration is needed.
Note you may need some other method if you're interested in checking whether or not migration is needed before deleting the database file (e.g. if you want user confirmation before deletion).
回答3:
The simplest way is to check Realm.schemaVersionAtPath(_:)
and seeing if that schema version is lower than your current schema version. You can also follow https://github.com/realm/realm-cocoa/issues/1692, which proposes adding a more exact API (one that doesn't require bumping your schema version) allowing you to detect if a migration would be required.
来源:https://stackoverflow.com/questions/30333959/detect-if-realm-io-db-needs-migration-if-so-destroy-it